Search code examples
lispcommon-lispfloating-accuracylispworks

Floating Point Precision Error


I am having problem with the LISP expression below. There is floating precision error while doing sum for floating point numbers.

CL-USER> (+ -380 -158.27 -35.52)

Actual:   -573.79004
Expected: -573.79000

Please suggest me how can I achieve the expected result in LISP (I am using Lispworks).


Solution

  • Floats are not exact

    Floats represent a subset of mathematical reals with certain precision, they are not exact numbers. Round off errors are inevitable.

    The ANSI Common Lisp standard provides for 4(!) levels of float precision: short, single, double, long (all implementations provide at least 2). Neither is exact, but ORACLE is probably using double, so if you stick with doubles, you should be fine.

    Theory

    Please read What Every Computer Scientist Should Know About Floating-Point Arithmetic.

    Use integers and ratios if you want exact numbers

    If you want to do exact computations, you should be using integers (e.g., representing currency as a number of cents, not dollars) or ratios.