Python get least significant digits from a float (without using string operations)

感情迁移 提交于 2019-12-24 01:19:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!