Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

10**-6 vs 0.000001 - just a representation or?

Tags:

python

math

In Python when I raise 10 to the minus sixth power:

>>> 10**-6
1e-06

It will display 1e-06.

Is there a noticable difference between writing 10**-6 and 0.000001 as displayed in the interpreter? Or is it just representation / formatting difference.

like image 537
Richard Knop Avatar asked Oct 28 '25 15:10

Richard Knop


2 Answers

To test if two float values are exactly equal, just use ==:

>>> 0.000001 == 10**-6
True

You may be confusing representation with the value. Python formats a float, when echoed in the interpreter, with the repr() function, and it represents the value by formatting with the g notation; this notation switches to using the scientific representation (e formatting) when the exponent gets large enough. repr() is effectively the same as format(value, '.16g').

You can format the numbers manually:

>>> format(10**-6, '.53f')
'0.00000099999999999999995474811182588625868561393872369'
>>> format(0.000001, '.53f')
'0.00000099999999999999995474811182588625868561393872369'

where .53f formats the value with up to 53 decimal numbers, a semi-arbitrary number based on the limits of what a floating point value can encode.

And indeed, both values are exactly the same. This was not a given; a float calculation can easily introduce small errors as float numbers are but approximations with binary fractions, after all.

like image 127
Martijn Pieters Avatar answered Oct 31 '25 03:10

Martijn Pieters


FWIW in order to convince yourself, you might use the marshal module to see a binary representation of the object:

>>> import marshal
>>> marshal.dumps(10**-6)
'g\x8d\xed\xb5\xa0\xf7\xc6\xb0>'
>>> marshal.dumps(0.000001)
'g\x8d\xed\xb5\xa0\xf7\xc6\xb0>'

As you can see, both values have the same binary representation.

like image 25
Sylvain Leroux Avatar answered Oct 31 '25 03:10

Sylvain Leroux