'math.pow of a very large integer in Python is wrong [duplicate]
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. 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
Solution 1:[1]
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. Use ** or the built-in pow() function for computing exact integer powers.
So just use **
>> 9**29+7**27
4710194409608608369201743232
Solution 2:[2]
math.pow converts the inputs to 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))
Solution 3:[3]
try it like this
>>> 9 ** 29 + 7 ** 27
4710194409608608369201743232
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Deepstop |
| Solution 2 | JacobIRR |
| Solution 3 | Michael Calve |
