10 ** - 6 versus 0.000001 - just a view or?

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

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

      

1e-06 will be displayed.

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

+3


source to share


3 answers


To check if two floating point values ​​match, just use ==

:

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

      

You can mislead the value view. Python formats a float

when echoing in the interpreter, with a function repr()

, and represents the value by formatting with a note g

; this notation switches to using scientific notation (formatting e

) when the exponent becomes large enough. repr()

is actually 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 to 53 decimal numbers, a semi-arbitrary number based on the constraints that a floating point value can encode.

Indeed, both meanings are the same. It was not given; calculating the float can easily introduce small errors, since floating point numbers are just approximations with binary fractions.

+5


source


FWIW, to convince yourself, you can use the marshal module to see the binary representation of an 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.

+2


source


There is never "precision" floating point, whereas numbers are logically the same, you cannot guarantee what you get 0.0

when you subtract them, but you can get a very small number (for example 1e-21

) due to rounding error.

As far as how it prints, it is a formatting issue.

+1


source







All Articles