10 ** - 6 versus 0.000001 - just a view or?
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.
source to share
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.
source to share