6

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?

joran
  • 169,992
  • 32
  • 429
  • 468
rubblesam
  • 61
  • 1

2 Answers2

4

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.

slava-kohut
  • 4,203
  • 1
  • 7
  • 24
  • 2
    Actually R doesn't treat very large numbers like that as integers. R will store that as a "numeric" value which is in this case would be a double floating point number (see `typeof(80538738812075974)`). So there is no integer overflow error message here. R will throw a integer overflow warning if you actually use integers (see `2e9L + 2e9L`). This is really more about the [well known problems with floating point arithmetic](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) which is shared with most modern programming languages. – MrFlick Sep 11 '19 at 18:24
  • @MrFlick thanks for your comment. I edited my post and acknowledged your contribution. – slava-kohut Sep 11 '19 at 18:34
3

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.

GKi
  • 37,245
  • 2
  • 26
  • 48