Python从浮点数中获取最低有效数字(不使用字符串操作)
假设我有浮点数 12345.6789,并且我想使用 python 中的位运算(v.2.6)将六个最低有效数字(即 45.6789)作为 int(即 456789)获得。
我该怎么做?
谢谢
PS 我不想使用字符串操作,即使它相当容易:对于任何浮点数 f:
int(str(int(f * 1000))[-10:])
编辑:这个原始问题是毫无意义的,如其中的评论所示。非常抱歉...下面显示了在不使用字符串的情况下获取最低有效数字的方法(使用整数和模数)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
但为什么??
But - WHY??
与您的字符串解决方案相关的是 python 2.7 中的浮点显示算法发生了变化:
无论您使用其中一种还是另一种,都存在一个问题,即确切地知道浮点数的精度是什么。假设你的算法的浮点数为 1.23。精度是多少?也许它被存储为 1.230,但它恰好以零数字结尾。因此,您必须知道要保留句点后的位数。
此外,位运算不适用于浮点数:
因此,您必须将浮点数乘以已知精度并使用模 (%),如其他海报所建议的那样。
Relevant for your string solution is that the float display algorithm changed in python 2.7:
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:
So you must multiply the float by your known precision and use modulo (%), as suggested by other posters.
但这不是位运算
but that is not bit operations