[R] problem with the precision of numbers

Hans W Borchers hwborchers at googlemail.com
Mon Jan 25 20:18:59 CET 2010


kayj <kjaja27 <at> yahoo.com> writes:
> 
> 
> Hi All,
> 
> thank you all for your help. I have tried Bill's script and it works! so I
> am trying to think what was the problem and it looks like it i sthe
> precision. so you defined a function of the precision and evaluates at
> precision=500. Bill, I was wondering how did you choose 500? is it
> arbitrary?
> 

Your question was "I was wondering if it is possible to increase the precision
using R", but you never told which accuracy you really need, As a rule of thumb,
the number of correct decimal digits is about 0.3 * precision, so for 50 digits
you could set the precision to 256 to Be on the safe side.

And if you are wondering how to compute the binomial coefficients with 'Rmpfr',
here's one possibility to do that:

    require(Rmpfr)

    mpfrChoose <- function(a, b, prec=128) {
        m1 <- mpfr(1, prec=prec)
        # r <- gamma(m1+a) / (gamma(m1+b) * gamma(m1+a-b))
        # if (is.whole(r)) return(r) else return(round(r))
        gamma(m1+a) / (gamma(m1+b) * gamma(m1+a-b))
    }

An advantage of using 'Rmpfr' is that the power of R can be applied, for
example vectorization, so avoid 'for' loops if possible:

    pr  <- 256
    m_1 <- mpfr(-1, pr)
    m1  <- mpfr(1, pr)

    i <- mpfr(0:80, pr)
    s <- sum((m_1^i) * mpfrChoose(80, i, prec=pr) * (m1-(i+1)*1/200)^200)

    print(s, digits=50)
    # 1 'mpfr' number of precision  256   bits
    # [1] 6.6568524789662037699673275771182135789699510194000e-20

Hans Werner

> 
> thanks again for your help
>



More information about the R-help mailing list