Bisection Method to find Square and Cube Roots
Hi,
I am new to Java and trying to write a program that uses the bisection method to calculate square roots. I need to calculate the roots good to 15 decimal places. I am only allowing the user to
When I run the program, it never actually enters the sqrtBisect method and instead repeatedly prompts the user for numbers. Thank you so much for you help, here is what I have so far:
import java.util.*;
public class Bisection {
public static double sqrtBisect(double target){
double high = 1000000; //Value above n
double low = 1; //Value below n
double mid = (high + low)/2;
boolean found = false;
while(!found && low<=high) {
if(target < (mid*mid))
high= mid-1;
else if(target > (mid*mid))
low = mid + 1;
else
found = true;
}
return mid;
}
public static void main(String [] args){
System.out.println("Please enter a number between 1 and 1000000.");
Scanner console;
console = new Scanner(System.in);
double n = console.nextInt(); //input number
while(n<1 || n> 1000000){
System.out.println("Number invalid, Please try again.");
n = console.nextInt();
}
double root = sqrtBisect(n);
System.out.println("The square root of " + n + " equals " +root+ ".");
}
}