CS 1073 Introductory Programming
|
| Newton's Method: Square root of 2 |
|---|
public class SquareRoot {
// findRoot: the root of a function
public double findRoot() {
double xOld = 2;
double xNew;
do {
xNew = xOld/2 + 1/xOld;
System.out.println("xNew: " + xNew);
if (Math.abs(xNew - xOld) < 1.0E-15) break;
xOld = xNew;
} while (true);
return xNew;
}
public static void main(String[] args) {
SquareRoot sq = new SquareRoot();
double root = sq.findRoot();
System.out.println("Root: " + root);
System.out.println("Sqrt(2): " + Math.sqrt(2));
}
}
|
Here are results of a run.
xNew: 1.5 xNew: 1.4166666666666665 xNew: 1.4142156862745097 xNew: 1.4142135623746899 xNew: 1.414213562373095 xNew: 1.414213562373095 Root: 1.414213562373095 Sqrt(2): 1.4142135623730951
| Newton's Method: Square root of n |
|---|
public class SquareRootN {
// findRoot: the root of a function
public double findRoot(double n) {
double xOld = 2;
double xNew;
do {
xNew = xOld/2 + n/(2*xOld);
System.out.println("xNew: " + xNew);
if (Math.abs(xNew - xOld) < 1.0E-15) break;
xOld = xNew;
} while (true);
return xNew;
}
public static void main(String[] args) {
double n = 3;
SquareRootN sq = new SquareRootN();
double root = sq.findRoot(n);
System.out.println("Root: " + root);
System.out.println("Sqrt(" + n + "): " + Math.sqrt(n));
}
}
|
Here are results of a run.
xNew: 1.75 xNew: 1.7321428571428572 xNew: 1.7320508100147274 xNew: 1.7320508075688772 xNew: 1.7320508075688772 Root: 1.7320508075688772 Sqrt(3.0): 1.7320508075688772
Now stick in 100 in place of 3 above.
xNew: 26.0 xNew: 14.923076923076923 xNew: 10.812053925455988 xNew: 10.030495203889796 xNew: 10.000046356507898 xNew: 10.000000000107445 xNew: 10.0 xNew: 10.0 Root: 10.0 Sqrt(100.0): 10.0
Now stick in 10000 in place of 3 above.
xNew: 2501.0 xNew: 1252.499200319872 xNew: 630.2416186767726 xNew: 323.05427461873035 xNew: 177.00441277925646 xNew: 116.75008971350636 xNew: 101.20156441035289 xNew: 100.00713307665073 xNew: 100.00000025438577 xNew: 100.0 xNew: 100.0 Root: 100.0 Sqrt(10000.0): 100.0