c# - Fibonacci's recurrence relation loss of precision on big digits -
i'm trying use binet's formula solve fibonacci's nth number o(1) time complexity.
class application { static void main(string[] c) { console.writeline($"fib(15) : expected 610 got : {fibonacci(15)}"); console.writeline($"fib(20) : expected 6765 got : {fibonacci(20)}"); console.writeline($"fib(100) : expected 354224848179261915075 got : {fibonacci(100)}"); console.readkey(); } private static biginteger fibonacci(int n) { double sqrt5 = math.sqrt(5d); return new biginteger((1/sqrt5)*math.pow((1 + sqrt5)/2, n) - (1/sqrt5)*math.pow((1 - sqrt5)/2, n)); } }
the following example works charm first 2 tests, fails quite huge amount third test (result 354224848179263111168
vs. 354224848179261915075
.
i guess might problem math.pow((1+sqrt5)/2,n)
part of formula, tried using formula using decimal
, double
, float
, biginteger
itself, , result never one.
is there way around problem or should accept can't using math.pow
?
edit tried using biginteger.pow
, use 1+sqrt5
needs biginteger
too, makes code @ end because of castings :
double sqrt5 = math.sqrt(5d); return new biginteger(1/sqrt5)*biginteger.pow(new biginteger(1 + sqrt5/2), n) - new biginteger(1 / sqrt5) * biginteger.pow(new biginteger((1 - sqrt5)/2), n);
and values returned zeroes.
using double have 15 , half digits of accuracy. can not expect more, output of integer conversion input.
that why binets formula not o(1) o(m(n)) n bit computations, using f[n] smaller 2^n m(n) cost of multiplication measure cost of exponentiation , logarithm.
Comments
Post a Comment