Python Float - Str - Float Weirdness

Python float - str - float weirdness

str(0.47000000000000003) give '0.47' and float('0.47') can be 0.46999999999999997.
This is due to the way floating point number are represented (see this wikipedia article)

Note: float(repr(0.47000000000000003)) or eval(repr(0.47000000000000003)) will give you the expected result, but you should use Decimal if you need precision.

python float formatting weirdness?

The str representation of a float truncates to 12 digits on Python 2. This is unfortunate. You have to print repr(a) to make sure you see enough precision to uniquely identify the float. There's probably a tiny difference that only shows up after 12 digits.

On Python 3, str and repr produce the same output for floats, so you wouldn't have this problem.

Python weird addition bug

From the Python docs

Note that this is in the very nature of binary floating-point: this is not a bug in Python, and it is not a bug in your code either (emphasis mine). You’ll see the same kind of thing in all languages that support your hardware’s floating-point arithmetic (although some languages may not display the difference by default, or in all output modes)

You should probably use the decimal module.

What is float('123.987') in Python?

The Python FAQ and tutorial address this issue pretty well, I think. More generally, both are excellent resources, well worth your time to browse if you have any interest in Python!-)

float deviation in python list

list.__str__ calls repr on its elements, where as print calls str:

>>> str(1.6)
'1.6'
>>> repr(1.6)
'1.6000000000000001'

Since floating point numbers are not guaranteed to be exact (and cannot be exact for values that can't be expressed as a * 2b for integers a,b), both representations are correct, or, in other words:

>>> 1.6 == 1.6000000000000001
True

Python float equality weirdness

What every computer scientist should know about floating point arithmetic.

>>> num = 1.00
>>> num
1.0
>>> num -= 0.95
>>> num
0.050000000000000044
>>> nickel = .05
>>> nickel
0.05

Python Float Division Not Exact

Short answer: Floats use finite-precision binary encoding to represent numbers, so various operations lose some precision.

The Wikipedia page has a lot of information (maybe too much).

See also: How do I use accurate float arithmetic in Python?

Python float numbers lose accuracy out of a tuple?

The only difference is the print. The number doesn't change, just its representation. You can reduce your problem to:

>>> 0.1457164443693023
0.1457164443693023
>>> print 0.1457164443693023
0.145716444369

(I guess (and this is only and merely a guess) this boils down to __repr__ vs __str__ or something along this line)



Related Topics



Leave a reply



Submit