简体   繁体   English

在python中打印一个非常大的整数

[英]Printing a very large integer in python

I am trying to print a very large number by calculating very large powers of an integer. 我试图通过计算一个整数的非常大的功率来打印一个非常大的数字。 Although my code is correct, i am not observing the desired output. 虽然我的代码是正确的,但我没有观察到所需的输出。

Generally, python interpreter can print very large integer as much as the system memory supports. 通常,python解释器可以打印与系统内存支持的非常大的整数。 With that assumption in mind below is the code i am running. 考虑到这一假设,下面是我正在运行的代码。

a = int(input())
b = int(input())
c = int(input())
d = int(input())

import math
if a in range(1,1001):
    if b in range(1,1001):
        if c in range(1,1001):
            if d in range(1,1001):
                print((math.pow(a,b)+math.pow(c,d)))

The output which i am observing is 我观察的输出是

4710194409608608302099333120

The output which is expected is 预期的输出是

4710194409608608369201743232

Can you please provide me pointers to how this can be solved? 能否请您指出如何解决这个问题? Input Values are: 输入值是:

a = 9
b = 29
c = 7
d = 27

You are running into the limits of floating point precision. 您正在遇到浮点精度的限制。 From the documentation: 从文档:

Unlike the built-in ** operator, math.pow() converts both its arguments to type float. 与内置**运算符不同,math.pow()将其参数转换为float类型。 Use ** or the built-in pow() function for computing exact integer powers. 使用**或内置的pow()函数来计算精确的整数幂。

So just use ** 所以只需使用**

>> 9**29+7**27
4710194409608608369201743232

math.pow converts the inputs to float math.pow将输入转换为float

The expected result you are showing is the result you get when you do: 您显示的预期结果是您执行此操作时获得的结果:

x = 9**29
y = 7**27
print(x+y)

The result you are seeing comes from this: 您看到的结果来自于:

x = float(9**29)
y = float(7**27)
print(int(x+y))

try it like this 试试这样

>>> 9 ** 29 + 7 ** 27
4710194409608608369201743232

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

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