Math.pow works strangely in Python

Viewed 58

Recently,I want to build a program to display an integer digit by digit, but I met some problems.
When I tried to print out math.pow(10,n), it worked as expected when n<23, but working strangely whenn>23.
Here are my test codes:

for i in range(0,31):
    print('(int) 10 to the',i,'th ==>',int(math.pow(10,i)))

The output:

*(int) 10 to the 23 th ==> 100000000000000008388608
(int) 10 to the 24 th ==> 999999999999999983222784
(int) 10 to the 25 th ==> 10000000000000000905969664
(int) 10 to the 26 th ==> 100000000000000004764729344
(int) 10 to the 27 th ==> 1000000000000000013287555072
(int) 10 to the 28 th ==> 9999999999999999583119736832
(int) 10 to the 29 th ==> 99999999999999991433150857216
(int) 10 to the 30 th ==> 1000000000000000019884624838656*

I also tried not to cast float to int.

for i in range(0,31):
print('(float) 10 to the',i,'th ==>',math.pow(10,i))

The output:

(float) 10 to the 23 th ==> 1.0000000000000001e+23
(float) 10 to the 24 th ==> 1e+24
(float) 10 to the 25 th ==> 1e+25
(float) 10 to the 26 th ==> 1e+26
(float) 10 to the 27 th ==> 1e+27
(float) 10 to the 28 th ==> 1e+28
(float) 10 to the 29 th ==> 1e+29
(float) 10 to the 30 th ==> 1e+30

What I expect math.pow(10,23) is something like 100...00.
Are there any ways that could achieve this?

1 Answers

Indeed this looks odd .

Math.pow() returns a float. The floating point number representation has limited precision. This is more apparent when numbers start getting very large or very small. The loss of precision cannot be fixed by converting from float to integer.

There's a way to print float numbers without scientific notation. See this answer.

So you could try and print the numbers like:

for i in range(0,31): 
print('(float) 10 to the',i,'th ==>','{:f}'.format(math.pow(10,i)))

However since Math.pow is of float type eventually the floating point precision limit will manifest itself.

Instead you can use the python exponentiation operator.

 for i in range(0,31): 
 print('(float) 10 to the',i,'th ==>',10 ** i)

The python exponentiation operator will always return an integer when the two arguments are integers. The operator is ** and assuming X ** Y it raises the number X to the power Y

Related