检查大型浮子是偶数还是奇怪

发布于 2025-02-06 12:50:54 字数 254 浏览 1 评论 0原文

我尝试使用Modulo操作员进行小型浮子,并且效果很好。 例如:5%2返回1

但是,对于其他在Python中读取为指数的大型浮子,它每次都会返回0,即使数字很奇怪。 这样:

295147905179352825855%2返回0,即使该数字显然很奇怪。

我可以做些什么来检查大型浮子而不将其视为指数?

I have tried using the modulo operator for small floats and it works perfectly fine.
For example: 5 % 2 returns 1.

But for other large floats that are read as exponential in python it just returns 0 every time even if the number is odd.
Like this:

295147905179352825855 % 2 returns 0 even though that number is clearly odd.

Is there anything I can do to check large floats without python reading it as exponential?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

┈┾☆殇 2025-02-13 12:50:54

您所说的是不是是真的。 2951479051793528255555%2应该起作用,因为 python对整数进行任意精确数学 。您的问题OTOH中没有浮点值

,如果您使用 float 喜欢29514790517935282825855.0显然在大多数现代平台上 python使用ieee-754 binary64格式只有53位精确且无法存储值,例如<代码> 295147905179352825855.0 。最接近的值是295147905179352825856.0显然是一个偶数号码

>>> 295147905179352825855 % 2
1
>>> 295147905179352825855.0 % 2
0.0
>>> format(295147905179352825855.0, '.20f')
'295147905179352825856.00000000000000000000'
>>> 295147905179352825856.0 == 295147905179352825855.0
True

What you said is not true. 295147905179352825855 % 2 should work because Python does arbitrary precision math on integers. There's no floating-point values in your question

OTOH if you use a float like 295147905179352825855.0 then it obviously won't work because on most modern platforms Python uses IEEE-754 binary64 format which has only 53 bits of precision and can't store values such as 295147905179352825855.0. The closest value is 295147905179352825856.0 which is clearly an even number

>>> 295147905179352825855 % 2
1
>>> 295147905179352825855.0 % 2
0.0
>>> format(295147905179352825855.0, '.20f')
'295147905179352825856.00000000000000000000'
>>> 295147905179352825856.0 == 295147905179352825855.0
True
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文