大斐波那契数的四舍五入

Rounding of big Fibonacci numbers

伙计们,希望你能指出我,我错过了什么。我是编程新手,现在正在为 Project Euler 解决问题。其中一项任务是计算斐波那契数列的偶数之和。我编写的代码通过了 5 项测试中的 4 项。这是:

//N is input (N<=4*10^16), let's find n by Binet's formula 

double a = log10(sqrt (5) * N);
double b = log10((1 + sqrt (5)) / 2);
int n = (int) (a / b); 

//Using same formula, we find every Fibonacci number till n
for (int i = 1; i <= n; i++){
  a = (1 + sqrt(5)) / 2;
  long fiboNum = Math.round (Math.pow(a,i) / sqrt(5));

这是我的问题:当我 运行 一个大数字测试时,在 F(71) 周围发生了一些舍入。 根据我的代码,F(71) 是 308 061 521 170 130,根据 WolphramAlpha 计算 308 061 521 170 129.

因此,最后的总和是错误的。

此外,在测试时我打印出所有数字并认识到,偶数每 3 个重复一次。但即使我将它简化为每三个数字求和的小循环,问题仍然存在。

如果我不使用 Math.round,我得到的序列是错误的...

double 的精度有限。尝试使用精度仅受可用内存大小限制的 BigDecimal

以下是使用 BigDecimals 计算平方根的方法:Square root of BigDecimal in Java

pow(): Java's BigDecimal.power(BigDecimal exponent): Is there a Java library that does it?

四舍五入:Java BigDecimal: Round to the nearest whole value

加法和除法等其他操作作为方法内置到 BigDecimal 中。