Java 指定精度_java-具有指定精度位数的牛顿方法

我正在尝试用Java编写一个计算数字的第n个根的函数.我正在为此使用牛顿方法.但是,用户应能够指定所需的精度位数.这是我遇到麻烦的部分,因为我的回答通常并不完全正确.相关代码在这里:http://pastebin.com/d3rdpLW8.我该如何解决此代码,以便始终给出至少p位精度的答案? (无需做过多的工作)

import java.util.Random;

public final class Compute {

private Compute() {

}

public static void main(String[] args) {

Random rand = new Random(1230);

for (int i = 0; i < 500000; i++) {

double k = rand.nextDouble()/100;

int n = (int)(rand.nextDouble() * 20) + 1;

int p = (int)(rand.nextDouble() * 10) + 1;

double math = n == 0 ? 1d : Math.pow(k, 1d / n);

double compute = Compute.root(n, k, p);

if(!String.format("%."+p+"f", math).equals(String.format("%."+p+"f", compute))) {

System.out.println(String.format("%."+p+"f", math));

System.out.println(String.format("%."+p+"f", compute));

System.out.println(math + " " + compute + " " + p);

}

}

}

/**

* Returns the n-th root of a positive double k, accurate to p decimal

* digits.

*

* @param n

* the degree of the root.

* @param k

* the number to be rooted.

* @param p

* the decimal digit precision.

* @return the n-th root of k

*/

public static double root(int n, double k, int p) {

double epsilon = pow(0.1, p+2);

double approx = estimate_root(n, k);

double approx_prev;

do {

approx_prev = approx;

// f(x) / f'(x) = (x^n - k) / (n * x^(n-1)) = (x - k/x^(n-1)) / n

approx -= (approx - k / pow(approx, n-1)) / n;

} while (abs(approx - approx_prev) > epsilon);

return approx;

}

private static double pow(double x, int y) {

if (y == 0)

return 1d;

if (y == 1)

return x;

double k = pow(x * x, y >> 1);

return (y & 1) == 0 ? k : k * x;

}

private static double abs(double x) {

return Double.longBitsToDouble((Double.doubleToLongBits(x) << 1) >>> 1);

}

private static double estimate_root(int n, double k) {

// Extract the exponent from k.

long exp = (Double.doubleToLongBits(k) & 0x7ff0000000000000L);

// Format the exponent properly.

int D = (int) ((exp >> 52) - 1023);

// Calculate and return 2^(D/n).

return Double.longBitsToDouble((D / n + 1023L) << 52);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值