Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A little diversion into floating point (im)precision, part 1

Tags:

Most mathematicians agree that:

eπi + 1 = 0

However, most floating point implementations disagree. How well can we settle this dispute?

I'm keen to hear about different languages and implementations, and various methods to make the result as close to zero as possible. Be creative!

like image 460
Chris Jester-Young Avatar asked Aug 04 '08 06:08

Chris Jester-Young


People also ask

What is floating-point error in Python?

It's a problem caused when the internal representation of floating-point numbers, which uses a fixed number of binary digits to represent a decimal number. It is difficult to represent some decimal number in binary, so in many cases, it leads to small roundoff errors.

How do you add a float value in Python?

Python sum of floats Output: 7.0 If you want to add floating point values with extended precision, you can use math. fsum() function.


2 Answers

It's not that most floating point implementations disagree, it's just that they cannot get the accuracy necessary to get a 100% answer. And the correct answer is that they can't.

PI is an infinite series of digits that nobody has been able to denote by anything other than a symbolic representation, and e^X is the same, and thus the only way to get to 100% accuracy is to go symbolic.

like image 119
Lasse V. Karlsen Avatar answered Sep 22 '22 23:09

Lasse V. Karlsen


Here's a short list of implementations and languages I've tried. It's sorted by closeness to zero:

  • Scheme: (+ 1 (make-polar 1 (atan 0 -1)))
    • 0.0+1.2246063538223773e-16i (Chez Scheme, MIT Scheme)
    • 0.0+1.22460635382238e-16i (Guile)
    • 0.0+1.22464679914735e-16i (Chicken with numbers egg)
    • 0.0+1.2246467991473532e-16i (MzScheme, SISC, Gauche, Gambit)
    • 0.0+1.2246467991473533e-16i (SCM)
  • Common Lisp: (1+ (exp (complex 0 pi)))
    • #C(0.0L0 -5.0165576136843360246L-20) (CLISP)
    • #C(0.0d0 1.2246063538223773d-16) (CMUCL)
    • #C(0.0d0 1.2246467991473532d-16) (SBCL)
  • Perl: use Math::Complex; Math::Complex->emake(1, pi) + 1
    • 1.22464679914735e-16i
  • Python: from cmath import exp, pi; exp(complex(0, pi)) + 1
    • 1.2246467991473532e-16j (CPython)
  • Ruby: require 'complex'; Complex::polar(1, Math::PI) + 1
    • Complex(0.0, 1.22464679914735e-16) (MRI)
    • Complex(0.0, 1.2246467991473532e-16) (JRuby)
  • R: complex(argument = pi) + 1
    • 0+1.224606353822377e-16i
like image 29
Chris Jester-Young Avatar answered Sep 23 '22 23:09

Chris Jester-Young