Dylan K
Dylan K

Reputation: 15

R addition of large and small numbers is ignoring the smaller values

I'm encountering a problem when adding larger numbers in R. The smaller values are getting ignored and it's producing an incorrect result.

For example, I've been using a binary to decimal converter found here: Convert binary string to binary or decimal value. The penultimate step looks like this:

2^(which(rev(unlist(strsplit(as.character(MyData$Index[1]), "")) == 1))-1)
[1] 1          2          32          64          256          2048          ...

I didn't include all number for length purposes, but when these numbers are summed, they will yield the integer value of the binary number. The correct result should be 4,919,768,674,277,575,011, but R is giving me a result of 4,919,768,674,277,574,656. Notice that this number is off by 355, which is the sum of the first 5 listed numbers.

I had thought it might have to do with a integer limit, but I tested it and R can handle larger numbers than what I need. Here's an example of something I tried, which again yielded an incorrect result:

2^64
[1] 18446744073709551616 #Correct Value
2^65
[1] 36893488147419103232 #Correct Value
2^64 + 2^65
[1] 55340232221128654858 #Correct Value
2^64 + 2^65 + 1
[1] 55340232221128654858 #Incorrect Value

It seems like there's some sort of problem with precision of large number addition, but I don't know how I can fix this so that I can get the desired result.

Any help would be greatly appreciated. And I apologize if anything is formatted improperly, this is my first post on the site.

Upvotes: 0

Views: 158

Answers (1)

akrun
akrun

Reputation: 886928

For large integers, we could use as.bigz from gmp

library(gmp)
as.bigz(2^64) + as.bigz(2^65) + 1
#   Big Integer ('bigz') :
#[1] 55340232221128654849

Upvotes: 2

Related Questions