Preventing R From Rounding

北城余情 提交于 2019-12-04 14:16:12

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.

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.

This would show you more digits for all numbers:

options(digits=15)

Or, if you want it just for a:

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