Python利用mpmath库+gmpy2库实现高斯勒让德算法,报错
from mpmath import mpfrom decimal import Decimal
import time
start_time = time.perf_counter()
mp.dps = 536870922
a0 = mp.mpf("1")
b0 = mp.sqrt("2") / 2
t0 = mp.mpf("0.25")
p0 = mp.mpf("1")
for i in range(50):
a1 = (a0 + b0) / 2
b1 = mp.sqrt(a0 * b0)
t1 = t0 - p0 * ((a0 - a1) ** 2)
p1 = 2 * p0
if a0 == a1:
break
else:
a0 = a1
b0 = b1
t0 = t1
p0 = p1
print("n", i)
pi = ((a1 + b1) ** 2) / (4 * t1)
print(pi)
with open(r"D:\Python\pi.txt", "w") as f:
f.write(str(pi))
f.close()
end_time = time.perf_counter()
t1=str(start_time)
t2=str(end_time)
use_time=Decimal(t2)-Decimal(t1)
print(use_time)
###报以下错误:C:\Users\User\AppData\Local\Programs\Python\Python39\python.exe D:\Python\高斯勒让德pi.py Traceback (most recent call last):File "D:\Python\高斯勒让德pi.py", line 14, in <module> t1 = t0 - p0 * ((a0 - a1) ** 2)File "<string>", line 18, in __pow__File "C:\Users\User\AppData\Local\Programs\Python\Python39\lib\site-packages\mpmath\libmp\libmpf.py", line 1069, in mpf_pow_int return normalize1(0, man, exp+exp, bc, prec, rnd)TypeError: arguments long, MPZ_Object*, PyObject*, long, long, char neededProcess finished with exit code 1如果精度设置低一点就不会报错,为什么呢?怎么解决?###
是精确到小数点后536870922位吗,感觉你的算法有问题,这么多位数再参与这个乘方运算太可怕了 本帖最后由 只手遮天我第一 于 2024-1-19 21:16 编辑
侃遍天下无二人 发表于 2024-1-19 20:21
是精确到小数点后536870922位吗,感觉你的算法有问题,这么多位数再参与这个乘方运算太可怕了
感谢兄弟提示,已修改,用decimal代替计算乘方
页:
[1]