user1538982
user1538982

Reputation: 1

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

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.

Upvotes: 0

Views: 2018

Answers (2)

Joshua Ulrich
Joshua Ulrich

Reputation: 176638

Use the int64 package:

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

Upvotes: 2

Dirk is no longer here
Dirk is no longer here

Reputation: 368181

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>

Upvotes: 2

Related Questions