Java Newton迭代

时间:2014-09-09 23:15:50

标签: java algorithm

我试图用我自己的函数制作一个平方根计算器,这个函数是sqrt并借用一个已经制作的计算器来测试精度。问题是每次我把猜测输入到屏幕后输入数字只是输入相同的数字,但它有一个.0。一个例子是,当我输入数字2时,我回到2.0这是错误的。请帮助:)

   import java.io.IOException;
import java.util.Scanner;

public class test {
/**
 * Main method.
 *
 * @param args
 *            the command line arguments
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    Scanner data = new Scanner(System.in);

    double root;
    /*
     * Put your main program code here; it may call myMethod as shown
     */
    System.out.println("Please enter a root to be calculated:");
    root = data.nextDouble();
    double actual = root;
    sqrt(root);
    sqrt_(actual);
    System.out.println(root);
    System.out.println(actual);
    /*
     * Close input and output streams
     */

}

/**
 * Computes estimate of square root of x to within relative error 0.01%.
 *
 * @param x
 *            positive number to compute square root of
 * @return estimate of square root
 */
private static double sqrt(double x) {

    double epilson = 0.0001;
    double approx = 1;
    int count = 0;
    while ((Math.abs(approx - (x / approx)) > (0.0001 * approx))
            && (count < 100)) {
        approx = 0.5 * (approx + (x / approx));
        count++;
    }
    return approx;

}

public static double sqrt_(double c) {
    if (c < 0) {
        return Double.NaN;
    }
    double EPS = 1E-15;
    double t = c;
    while (Math.abs(t - c / t) > EPS * t) {
        t = (c / t + t) / 2.0;
    }
    return t;
}
}

1 个答案:

答案 0 :(得分:3)

您只是忘记分配返回值。

root = sqrt(root);
actual = sqrt_(actual);