Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R not calculating large cubes correctly?

Tags:

r

There's been some news lately about the discovery of three cubes that sum to 42. Namely, Andrew Sutherland and Andrew Booker discovered that (-80538738812075974)^3 + 80435758145817515^3 + 12602123297335631^3=42 (https://math.mit.edu/~drew/)

I was tinkering with this a bit, and I'm not getting 42 in R.

I do get it in other places (WolframAlpha), but R gives me this:

> (-80538738812075974)^3 + 80435758145817515^3 + 12602123297335631^3
[1] 1.992544e+35

Any idea what I'm doing wrong? Is it a limitation with large numbers in R? Or am I (very probably) just doing something dumb?

like image 981
rubblesam Avatar asked Sep 11 '19 17:09

rubblesam


2 Answers

UPDATE

As pointed out by @MrFlick, this is a well-known floating point arithmetic issue. R stores large numbers in your example as double precision numbers.

Also, be aware of integer overflow. See a related discussion here. Note that base R will not throw an error (just a warning) when integer overflow occurs.The bit64 package may help sometimes, but won't do the job in your case the accuracy it provides is still not enough.

like image 57
slava-kohut Avatar answered Nov 14 '22 23:11

slava-kohut


If you want to calculate with large (integer) numbers in R you can use the gmp library like:

library(gmp)
as.bigz("-80538738812075974")^3 + as.bigz("80435758145817515")^3 + as.bigz("12602123297335631")^3
#[1] 42

#or even better use also Integer in the exponent:
as.bigz("-80538738812075974")^3L + as.bigz("80435758145817515")^3L + as.bigz("12602123297335631")^3L

As @mrflick pointed already out you are using numeric - double. So the calculated result is approximately right. When using Integer you get warnings and R will convert it to numeric:

(-80538738812075974L)^3L + 80435758145817515L^3L + 12602123297335631L^3L
#[1] 1.992544e+35
#Warning messages:
#1: non-integer value 80538738812075974L qualified with L; using numeric value 
#2: non-integer value 80435758145817515L qualified with L; using numeric value 
#3: non-integer value 12602123297335631L qualified with L; using numeric value 

Note that you have to give a string to as.bigz. When writing a number R will treat it as double or convert, as above, large integer numbers, to double and might lose precision.

like image 28
GKi Avatar answered Nov 14 '22 23:11

GKi