Python:修复复杂数学中最多 4 个浮点数结果

Python: Fix up to 4 float number result in Complex Math

提问人:Otoniel Ramirez 提问时间:10/2/2023 最后编辑:BarmarOtoniel Ramirez 更新时间:10/2/2023 访问量:43

问:

我正在 Python 中求解一个二次方程,但结果给了我 16 位小数

import cmath

a = 1
b = -4
c = 1
5
#Calculate the discriminant
d = (b**2) - (4*a*c)
#Find the two solutions:
sol1 = (-b-cmath.sqrt(d))/(2*a)
sol2 = (-b+cmath.sqrt(d))/(2*a)
print("The solutions are {0} and {1} ".format(sol1,sol2))

解决方案是 (0.2679491924311228+0j) 和 (3.732050807568877+0j)

我正在尝试这个:

print("The solutions are %0.4{0} and %0.4{1} ".format%(sol1,sol2)

#But 不起作用”

Python 数学 浮点 精度

评论

0赞 Barmar 10/2/2023
你把格式放在里面:{}{0:.4f}
1赞 Otoniel Ramirez 10/2/2023
谢谢 Barmar,这就是解决方案,而且不需要在 0 数字之前放置 % 符号或 0 数字
0赞 Reilas 10/2/2023
@OtonielRamirez, print(f“解决方案是 {sol1:.4f} 和 {sol2:.4f} ”).string — 常用字符串操作 — Python 3.11.5 文档

答: 暂无答案