Bisection Method to find Square and Cube Roots

• 05-07-2011, 12:42 AM
tecnicamente
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+ ".");
}
}
• 05-07-2011, 01:01 AM
tecnicamente
Fixed it.
Sorry,
tec
• 05-07-2011, 01:03 AM
pbrockway2
HI, welcome to the forums.

When you post code, use the "code" tags. You put [code] at the start of the code and [/code] at the end, that way the code will preserve indentation and be readable.

Quote:

When I run the program, it never actually enters the sqrtBisect method and instead repeatedly prompts the user for numbers.

I'm not so sure about this. What actually happens when you run the program: ie what do you see? (not what do you think causes what you see)

 slow ;( But welcome anyway! ANd my comment stands, when debugging: objectivity beats speculation every time...