題目描述
計算一個數字的立方根,不使用庫函數
詳細描述:
接口說明
原型:
public static double getCubeRoot(double input)
輸入:double 待求解參數
返回值:double 輸入參數的立方根
輸入描述
待求解參數 double類型
輸出描述
輸入參數的立方根 也是double類型
輸入例子
216
輸出例子
6.0
算法實現
import java.util.Scanner;
/**
* Declaration: All Rights Reserved !!!
*/
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
while (scanner.hasNext()) {
double d = scanner.nextDouble();
System.out.printf("%.1f", getCubeRoot(d));
}
scanner.close();
}
/**
* 使用牛頓迭代法求立方根
* 已知利用牛頓迭代法求方程F(x)=0的解的公式爲X[n+1] = X[n] - F(X[n])/F'(X[n]),
* 其中x[n]爲第n次利用此公式求得值。
* 假如函數F(X) = X^m - a, 則根據牛頓迭代法第n+1次求方程F(x) = 0的解爲X[n+1],
* 且X[n+1] = (1-1/m)*X[n] +a/(n*X[n]^(m-1)) - (X[n]*X[n]*X[n]+a)/3*X[n]*X[n]。
*
* @param x
* @return
*/
private static double getCubeRoot(double x) {
double x0;
double x1 = x;
do {
x0 = x1;
x1 = 2.0 / 3.0 * x0 + x / 3.0 / (x0 * x0);
} while (Math.abs(x1 - x0) > 0.000001);
return x1;
}
}