Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
946 views
in Technique[技术] by (71.8m points)

precision - How to work with large numbers in R?

I would like to change the precision in a calculation of R. For example I would like to calculate x^6 with x = c(-2.5e+59, -5.6e+60). In order to calculate it I should change the precision in R, otherwise the result is Inf, and I don't know how to do it.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Livius points out in his comment, this is an issue with R (and in fact, most programming language), with how numbers are represented in binary.

To work with extremely large/small floating point numbers, you can use the Rmpfr library:

install.packages("Rmpfr")
library("Rmpfr")
x <- c(-2.5e+59, -5.6e+60)
y <- mpfr(x, 6)  # the second number is how many precision **bits** you want - NB: not decimal places!
y^6
# 2 'mpfr' numbers of precision  6   bits 
# [1] 2.50e356 3.14e364

To work with numbers that are even larger than R can handle (e.g. exp(1800)) you can use the "Brobdingnag" package:

install.packages("Brobdingnag")
library("Brobdingnag")

## An example of a single number too large for R: 
10^1000.7
# [1] Inf

## Now using the Brobdingnag package:
10^as.brob(1000.7)
# [1] +exp(2304.2)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...