问题
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 that?
Thanks
PS I do not want to use string operations even if it would be rather easy to: for any float f:
int(str(int(f * 1000))[-10:])
EDIT: This original question is pointless, as shown by comments within. Many apologies... instead methods on getting the least significant digits without using strings are shown below (using ints and modulus)
回答1:
>>> a = 12345.6789
>>> b = int(a*10000)
>>> b
123456789
>>> c = b % 1000000
>>> c
456789
But - WHY??
回答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 call last):
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.
回答3:
>>> int(12345.6789*10000)%1000000
456789
but that is not bit operations
来源:https://stackoverflow.com/questions/5634714/python-get-least-significant-digits-from-a-float-without-using-string-operation