Python从浮点数中获取最低有效数字(不使用字符串操作)

发布于 2024-10-31 22:18:02 字数 291 浏览 1 评论 0原文

假设我有浮点数 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

过去的过去 2024-11-07 22:18:02
>>> a = 12345.6789
>>> b = int(a*10000)
>>> b
123456789
>>> c = b % 1000000
>>> c
456789

但为什么??

>>> a = 12345.6789
>>> b = int(a*10000)
>>> b
123456789
>>> c = b % 1000000
>>> c
456789

But - WHY??

沫离伤花 2024-11-07 22:18:02

与您的字符串解决方案相关的是 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

无论您使用其中一种还是另一种,都存在一个问题,即确切地知道浮点数的精度是什么。假设你的算法的浮点数为 1.23。精度是多少?也许它被存储为 1.230,但它恰好以零数字结尾。因此,您必须知道要保留句点后的位数。

此外,位运算不适用于浮点数:

>>> 12345.6789 << 4
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for <<: 'float' and 'int'

因此,您必须将浮点数乘以已知精度并使用模 (%),如其他海报所建议的那样。

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.

疾风者 2024-11-07 22:18:02
>>> int(12345.6789*10000)%1000000
456789

但这不是位运算

>>> int(12345.6789*10000)%1000000
456789

but that is not bit operations

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文