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.
Asked
Active
Viewed 1.2k times
12

Axeman
- 32,068
- 8
- 81
- 94

user3430764
- 241
- 1
- 2
- 4
-
1This is more about R than RStudio -- and if it's an issue of moving beyond double precision, then there are other issues to worry about (like the precision of the libraries R links to). This might also be one of those times where exponentiation (usually implemented in language backends with calls to `exp()`) isn't the same floating point operation as repeated multiplication, which could have important consequences when working near the edge of precision. – Livius Mar 17 '14 at 23:23
-
This http://stat.ethz.ch/R-manual/R-patched/library/base/html/zMachine.html should help you understand the limits of your architecture which can be a good springboard for looking for packages that will help you overcome any built-in limitations. – hrbrmstr Mar 18 '14 at 00:47
-
Thank you for your help and the time you spended for answering – user3430764 Mar 18 '14 at 15:21
1 Answers
12
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)

pglpm
- 516
- 4
- 14

Scott Ritchie
- 10,293
- 3
- 28
- 64
-
1There is a section in the [Numerical Mathematics Task View](http://cran.r-project.org/web/views/NumericalMathematics.html) devoted to "Multi-Precision Arithmetic and Symbolic Mathematics". – Joshua Ulrich Mar 18 '14 at 11:12
-
-
1@PeterPan I've updated my answer to include information on numbers that start out larger than R can handle – Scott Ritchie Apr 20 '17 at 00:18