# Thread: Bisection Method to find Square and Cube Roots

1. Member
Join Date
May 2011
Posts
3
Rep Power
0

## 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){
n = console.nextInt();
}
double root = sqrtBisect(n);
System.out.println("The square root of " + n + " equals " +root+ ".");
}
}

2. Member
Join Date
May 2011
Posts
3
Rep Power
0
Fixed it.
Sorry,
tec

3. Moderator
Join Date
Feb 2009
Location
New Zealand
Posts
4,712
Rep Power
14
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.

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...

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•