I'm writing a program that solves a square root. The program seems to work properly up until it reaches the while ((x1-x2)>dif)
loop and then runs forever with out returning the final x2
. Thanks for reading!
import java.util.Scanner;
public class lab13 {
static double getSqrt(double s) {
double dif = .000001;
double S = 0;
if (s == 0)
return 0;
double a = s;
int n = 0;
if (a >= 100) {
while (a >= 100) {
a /= 100;
n++;
}
}
else {
while (a < 1) {
a *= 100;
n --;
}
}
System.out.println(a + " " + n);
if (a < 10) {
S = 2*Math.pow(10, n);
}
else {
S = 6*Math.pow(10, n);
}
System.out.println(S);
double x1, x2;
x1=S;
System.out.println(x1);
x2 = (0.5)*(x1+(s/x1));
System.out.println(x2);
while ((x1-x2)>dif) {
x2 = (0.5)*(x1+(s/x1));
}
System.out.println(x2);
return x2;
}
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.print("Enter n (negative to stop):");
double n = in.nextDouble();
while (n >= 0) {
System.out.println(getSqrt(n));
System.out.println();Math.sqrt(n);
System.out.print("Enter n(negative to stop):");
n = in.nextDouble();
System.out.println(getSqrt(n));
}
}
}
Pay attention to what you're doing.
x2 = (0.5)*(x1+(s/x1));
The right side of that expression is constant inside the loop, so the value of x2 never changes.
while ((x1-x2)>dif) {
x2 = (0.5)*(x1+(s/x1));
}
The trouble is that x2
is being updated but x1
is not. For Newton's method to work x1
needs to be the previous guess, but since it's not being updated x1
is perpetually the first guess .
while ((x1-x2)>dif) {
double prev = x2;
x2 = (0.5)*(x1+(s/x1));
x1 = prev;
}
while ((x1-x2)>dif) {
x2 = (0.5)*(x1+(s/x1));
}
Neither x1
nor dif
nor s
do not change inside the while
. x2
changes from the original value but its value is set to the same value in each iteration (since it depends only of x1
and s
). So either the loop runs just once or it will run forever.
Why do you expect this not to fail?
Thats because in your code
while ((x1-x2)>dif) {
x2 = (0.5)*(x1+(s/x1));
}
x2 never increases, never changes its values, x1-x2
remains constant and > diff, thus you never exit out of the loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.