Python Get Least Significant Digits From A Float (without Using String Operations)
Assuming I have the float 12345.6789 and I want to get the six least significant digits (i.e. 45.6789) as an int (i.e. 456789) using bit operations in python (v. 2.6). How do I do
Solution 1:
>>>a = 12345.6789>>>b = int(a*10000)>>>b
123456789
>>>c = b % 1000000>>>c
456789
But - WHY??
Solution 2:
Relevant for your string solution is that the float display algorithm changed in python 2.7:
Python 2.6.6 (r266:84292, Sep 15 2010, 15:52:39)
>>>12345.6789
12345.678900000001
Python 2.7.0+ (r27:82500, Sep 15 2010, 18:04:55)
>>>12345.6789
12345.6789
Whether you use one or the other, there's a problem knowing what, exactly, is the precision of a floating point number. Say your algorithm is given the float 1.23. What's the precision? Maybe it was stored as 1.230, but it just happened to end with a zero digit. So you must know how many digits after the period you wish to preserve.
Also, bit operations do not work on floats:
>>>12345.6789<<4
Traceback (most recent calllast):
File "<stdin>", line 1, in<module>
TypeError: unsupported operand type(s) for<<: 'float'and'int'
So you must multiply the float by your known precision and use modulo (%), as suggested by other posters.
Solution 3:
>>>int(12345.6789*10000)%1000000
456789
but that is not bit operations
Post a Comment for "Python Get Least Significant Digits From A Float (without Using String Operations)"