Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing R From Rounding

How do I prevent R from rounding?

For example,

> a<-893893084082902
> a
[1] 8.93893e+14

I am losing a lot of information there. I have tried signif() and it doesn't seem to do what I want.

Thanks in advance!

(This came up as a result of a student of mine trying to determine how long it would take to count to a quadrillion at a number per second)

like image 620
Michael Avatar asked Jul 12 '11 19:07

Michael


3 Answers

It's not rounding; it's just the default format for printing large (or small) numbers.

a <- 893893084082902
> sprintf("%f",a)
[1] "893893084082902.000000"

See the "digits" section of ?options for a global solution.

like image 97
Joshua Ulrich Avatar answered Nov 18 '22 13:11

Joshua Ulrich


This would show you more digits for all numbers:

options(digits=15)

Or, if you want it just for a:

print(a, digits=15)
like image 36
Tommy Avatar answered Nov 18 '22 15:11

Tommy


To get around R's integer limits, you could use the gmp package for R: http://cran.r-project.org/web/packages/gmp/index.html

I discovered this package when playing with the Project Euler challenges and needing to do factorizations. But it also provides functions for big integers.

EDIT: It looks like this question was not really one about big integers as much as it was about rounding. But for the next space traveler who comes this way, here's an example of big integer math with gmp:

Try and multiply 1e500 * 1e500 using base R:

> 1e500 * 1e500
[1] Inf

So to do the same with gmp you first need to create a big integer object which it calls bigz. If you try to pass as.bigz() an int or double of a really big number, it will not work, because the whole reason we're using gmp is because R can't hold a number this big. So we pass it a string. So the following code starts with string manipulation to create the big string:

library(gmp)
o <- paste(rep("0", 500), collapse="")
a <- as.bigz(paste("1", o, sep=""))
mul.bigz(a, a)

You can count the zeros if you're so inclined.

like image 7
JD Long Avatar answered Nov 18 '22 13:11

JD Long