Search code examples
emacsnumberslispelispbignum

Lisp interactive emacs multiplying incorrectly


I'm running the following code on Emacs Lisp Interaction:

(defun square (x) (* x x))
(square (square (square 1001)))

which is giving me 1114476179152563777. However, the ((1001^2)^2)^2 is actually 1008028056070056028008001. How is this possible?


Solution

  • Emacs Lisp doesn't implement bignums, it uses the machine's integer type. The range of integers it supports is between most-negative-fixnum and most-positive-fixnum. On a 64-bit system, most-positive-fixnum will be 261-1, which has about 20 decimal digits.

    See Integer Basics in the Elisp manual.

    The correct result of your calculation is 25 digits, which is much larger than this. The calculation overflows and wraps around. It should be correct modulo 262.

    You could use floating point instead. It has a much larger range, although very large numbers lose precision.

    (square (square (square 1001.0)))
    1.008028056070056e+24