简体   繁体   English

Python:大型浮点数的小数部分

[英]Python: Decimal part of a large float

I'm trying to get the decimal part of (pow(10, i) - 1)/23 for 0 < i < 50 . 我试图得到(pow(10, i) - 1)/23的小数部分为0 < i < 50 I have tried 我努力了

(pow(10, i) - 1)/23 % 1

in Python 3 but I get 0.0 for all values of i greater than 17. 在Python 3中,但是对于i大于17的所有值,我得到0.0

How can I extract the decimal part of a large integer in Python? 如何在Python中提取大整数的小数部分?

To preserve precision, I'd probably use the fractions module: 为了保持精度,我可能会使用分数模块:

>>> from fractions import Fraction
>>> Fraction(10)
Fraction(10, 1)
>>> Fraction(10)**50
Fraction(100000000000000000000000000000000000000000000000000, 1)
>>> Fraction(10)**50-1
Fraction(99999999999999999999999999999999999999999999999999, 1)
>>> (Fraction(10)**50-1)/23
Fraction(99999999999999999999999999999999999999999999999999, 23)
>>> ((Fraction(10)**50-1)/23) % 1
Fraction(5, 23)
>>> float(((Fraction(10)**50-1)/23) % 1)
0.21739130434782608

although using the decimal module would be another option. 虽然使用十进制模块将是另一种选择。

update: wait, on second thought, the answer here is always going to be ((10^n-1) % 23)/23 , so the above is significant overkill (although it does scale up better to more complex problems). 更新:等等,第二个想法,这里的答案总是((10^n-1) % 23)/23 ,所以上面是显着的过度杀伤(虽然它确实扩大到更复杂的问题)。 We can even take advantage of the three-argument pow call: 我们甚至可以利用三参数pow调用:

>>> pow(10, 50, 23)
6
>>> pow(10, 50, 23) - 1
5
>>> (pow(10, 50, 23) - 1) % 23 # handle possible wraparound
5
>>> ((pow(10, 50, 23) - 1) % 23) / 23.0
0.21739130434782608

One option that does not use other modules is 一个不使用其他模块的选项是

N = 10**i - 1
remainder = N % 23
print remainder / 23.0

Of course easily written on one line as well. 当然也很容易写在一行上。

Using the three argument form of pow , which performs modular exponentation , you can avoid large numbers alltogether, for improved performance. 使用执行模块化指数 的pow三个参数形式 ,可以完全避免大量数据,从而提高性能。

((pow(10, i, 23) + 22) % 23) / 23.0

You mean: "how can I extract the decimal part of a large float in Python? There is no "decimal" part anymore, because the comma is floating ... :-) 你的意思是:“如何在Python中提取大型浮点数的小数部分?不再有”十进制“部分,因为逗号是浮动的 ... :-)

On Python 2.7, for i=20 (I divided by 23.0 in order to get a float result), the result is 4.347826086956522e+18 . 在Python 2.7上,对于i=20 (为了获得浮点结果,我除以23.0),结果为4.347826086956522e+18 There are 16 digits for a number of magnitude 10^18. 数字10 ^ 18有16位数字。 Hence, there is no digit "after the comma" (this may be still incorrect für i=20 because it could be that not all digits have been printed, but at least you get the concept of what I mean). 因此,没有数字“逗号后”(这可能是仍然不正确献给i=20 ,因为它可能是,并非所有的数字都被打印,但至少你得到我的意思的概念)。

You have to apply a library that is implementing arbitrary-precision arithmetics for large i . 您必须应用一个为大型i实现任意精度算术的库。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM