Reputation: 13570
I'm calculating Fibonacci numbers in R with this code:
fib <- function(n) {
a = 0
b = 1
for (i in 1:n) {
tmp = b
b = a
a = a + tmp
}
return (a)
}
sprintf("%.0f",fib(79))
From fib(79) onwards I'm getting inaccurate results. For instance: fib(79) = "14472334024676220" when the right result, according to this web, should be: fib(79)=14472334024676221
Using the function fibonacci from the package numbers I get the same inaccurate results. I assume this is because of the number precision in R.
How can I bypass this limitation and get accurate Fibonacci numbers in R?
Upvotes: 4
Views: 428
Reputation: 597
You reached the limits of double precision floating-point arithmetics which has 16 decimal digits of accuracy. You do require 17 here. AFAIK R does not have a variable type with greater precision.
To bypass this you might want to split your operands and sum'em separately. A state-of-the-art way around this is to convert your operands to character, parse them from astern, adding digit by digit, paying attention for carryover.
Upvotes: 2
Reputation: 13570
Thank you for voting the question. My reputation is above 10 so I can post it rigth now :). I've got a pretty simple solution using the package gmp (a library mentioned as well in the link provided by Ben Bolker) to sum large integers.
require(gmp)
fib <- function(n) {
a = 0
b = 1
for (i in 1:n) {
tmp = b
b = a
a = add.bigz(a, tmp) # gmp function
}
return (a)
}
fib(79)
The result is the right Fibonacci number, fib(79): 14472334024676221. I tested it for even larger integers fib(5000), 1045 digits, and the result seems accurate to the last digit.
Upvotes: 4