why as.numeric function in R doesn't work properly?

假如想象 提交于 2019-12-11 18:33:10

问题


I have these two characters and the "as.numeric" function doesn't work same for them. Can anyone help me why this is happening?

options(digits=22)

a="27"

as.numeric(a)

[1] 27.00000000000000000000

a="193381411288395777"

as.numeric(a)

[1] 193381411288395776.0000

It can be seen that in the second case the last digit is not "7" and it is "6". Basically the "as.numeric" function decreases 1 unit from the number in the second case.

Any help is appreciated.


回答1:


You need to learn about the limits of representation of exact numbers. R can tell you what it has:

R> .Machine
$double.eps
[1] 2.22045e-16

$double.neg.eps
[1] 1.11022e-16

$double.xmin
[1] 2.22507e-308

$double.xmax
[1] 1.79769e+308

$double.base
[1] 2

$double.digits
[1] 53

$double.rounding
[1] 5

$double.guard
[1] 0

$double.ulp.digits
[1] -52

$double.neg.ulp.digits
[1] -53

$double.exponent
[1] 11

$double.min.exp
[1] -1022

$double.max.exp
[1] 1024

$integer.max
[1] 2147483647

$sizeof.long
[1] 8

$sizeof.longlong
[1] 8

$sizeof.longdouble
[1] 16

$sizeof.pointer
[1] 8

R>



回答2:


Use the int64 package:

library(int64)
> as.int64("193381411288395777")
[1] 193381411288395777


来源:https://stackoverflow.com/questions/11568385/why-as-numeric-function-in-r-doesnt-work-properly

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