Inaccurate results calculating Fibonacci numbers in R

I calculate the Fibonacci numbers in R using 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))

Starting with fib (79), I get inaccurate results. For example: fib (79) = "14472334024676220", when the correct result according to this web should be: fib (79) = 14472334024676221

Using the fibonacci function from the numbers package I get the same inaccurate results. I assume this is due to the accuracy of the number in R.

How can I get around this restriction and get the exact Fibonacci numbers in R?

+4
source share
2 answers

, . 10, .:). , gmp (, , ), .

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)

, fib (79): 14472334024676221. fib (5000), 1045 , .

+4

, 16 . 17. AFAIK R .

, . , , , , .

+2

Source: https://habr.com/ru/post/1532470/


All Articles