Math.pow在Python中的工作方式很奇怪



最近,我想构建一个程序来逐位显示整数,但是我遇到了一些问题
当我尝试打印math.pow(10,n)时,它在n<23时按预期工作,但在n>23时工作异常。
以下是我的测试代码:

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

输出:

*(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*

我也尽量不将float转换为int。

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

输出:

(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

我所期望的math.pow(10,23)类似于100...00
有什么办法可以做到这一点吗?

事实上,这看起来很奇怪。

Math.pow((返回一个浮点值。浮点数字表示的精度有限。当数字开始变得非常大或非常小时,这一点就更加明显了。无法通过从浮点转换为整数来修复精度损失。

有一种方法可以在不使用科学符号的情况下打印浮点数。看看这个答案。

所以你可以试着打印这样的数字:

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

然而,由于Math.pow是浮点类型,浮点精度限制最终会显现出来。

相反,您可以使用python求幂运算符

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

当两个参数为整数时,python求幂运算符将始终返回一个整数。运算符为**,假定为X ** Y,则它将数字X提升为Y的幂

最新更新