Project Euler Problem 80-高精度开方-牛顿逼近法
Project Euler Problem 80-高精度开方-牛顿逼近法
BlackJoker 发表于2年前
Project Euler Problem 80-高精度开方-牛顿逼近法
• 发表于 2年前
• 阅读 30
• 收藏 0
• 评论 0
It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.

The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.

For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.

``````// 0.0000001是精度，f是待求根的函数，df是f的导数，x0是初值
public static double newtonMehtod(F f, DF df, double x0) {
double x1 = x0 - f.f(x0) / df.df(x0);
while (Math.abs(x1 - x0) > 0.0000001) {
x0 = x1;
x1 = x0 - f.f(x0) / df.df(x0);
}
return x1;
}
//函数f(x)
public interface F {
double f(double x);
}
//f(x)的导数f'(x)
public interface DF {
double df(double x);
}``````

F和DF的实现类没贴上来。

``````static int prec = 100;
static BigDecimal precE;
static {
String e = "-0.";
for (int i = 0; i < prec; i++) {
e += "0";
}
e += "1";
precE = new BigDecimal(e);
}

public static BigDecimal newtonMehtod(F f, DF df, double x00) {
BigDecimal x0 = BigDecimal.valueOf(x00);
.divide(df.df(x0), BigDecimal.ROUND_HALF_EVEN).negate());
x0 = x1;
.negate());
}
return x1;
}

public interface F {
BigDecimal f(BigDecimal x);
}
public interface DF {
BigDecimal df(BigDecimal x);
}``````

1.4142135623730950488016887242096980785696718
753769480731766797379907324784621070388503875
343276415727350138462309122970249248360558507
372126441214970999358314132226659275055927557
999505011527820605714701095599716059702745345
968620147285174186408891986095523.

×