rdigit

How to get my function to take higher values


In R I have writing this function

ifun = function(m)  {
o=c()
for(k in 1:m) {
o[k]= prod(1:k)/ prod(2*(1:k)+1  )
}
o_sum=2*(1+sum(o)) # Final result   
print(o_sum)
}

I want the values for ifun() for high values. For example

 sprintf("%.100f",ifun(170) ) 

gives this output:

[1] 3.141593
[1] "3.1415926535897931159979634685441851615905761718750000000000000000000000000000000000000000000000000000"

But when I take higher values it can give me any value. For example

sprintf("%.100f",ifun(180) ) 

gives me this output

[1] NaN
[1] "NaN"

How can I rewrite me code so I can take ifun for larger values? Also, I use this function to approximate pi but for

> ifun(x>50)

it gives me the same result over and over again and don't make my approximation any better.


EDIT

I tried to use the method on Macin series as well I wrote this in R

mac = function(m, approx=TRUE){   
o1 = as.bigq(NULL)   
o2 = as.bigq(NULL)
for(k in 1:m) {
k <- as.bigq(k)
     o1 = c(o1, 1/((2*k+1)*5^(2*k+1))  *(-1)^k)
     o2 = c(o2, 1/((2*k+1)*239^(2*k+1))  *(-1)^k)

   }   
  o_sum = 16*(1/5+sum(o1)) -4*(1/239+sum(o2))   
  if(approx){
     as.numeric(o_sum)   
  } else{
     o_sum   } }

 library(Rmpfr)  x <- mac(250, approx=FALSE)  mpfr(x,256)

This gives me a strange output namely

> 1 'mpfr' number of precision  256   bits  [1]
> 3.1415926535897934 18913264129286527160857809883357101405

It only gives me the first 16 correct digits, it can't give me more. What can be the reason for this?


Solution

  • Use gmp. It can give the exact result as a rational number if you want.

    library(gmp)
    
    ifun = function(m, approx=TRUE){
      o = as.bigq(NULL)
      for(k in 1:m) {
        r <- as.bigz(1:k)
        o = c(o, prod(r)/ prod(2*r+1 ))
      }
      o_sum = 2*(1+sum(o)) 
      if(approx){
        as.numeric(o_sum)
      }else{
        o_sum
      }
    }
    

    > ifun(4, approx=FALSE)
    Big Rational ('bigq') :
    [1] 976/315
    > ifun(180)
    [1] 3.141593
    

    Edit

    Actually to convert the exact rational number to a decimal number, it is better to use the Rmpfr library:

    > library(Rmpfr)
    > x <- ifun(250, approx=FALSE)
    > mpfr(x,256)
    1 'mpfr' number of precision  256   bits 
    [1] 3.14159265358979323846264338327950288419716939937510582097494459230781640628613