Preventing R From Rounding

人走茶凉 提交于 2019-12-06 08:49:15

问题


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)


回答1:


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.




回答2:


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.




回答3:


This would show you more digits for all numbers:

options(digits=15)

Or, if you want it just for a:

print(a, digits=15)


来源:https://stackoverflow.com/questions/6669681/preventing-r-from-rounding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!