我想打印1-10的平方根(向后)。
我也希望打印出这些相邻平方根的差异。
import math as m
for i in range(10, -1, -1):
print str(i) + ": " + str(m.sqrt(i))
print str(m.sqrt(i) - m.sqrt(i-1))
我目前收到数学域错误。
答案 0 :(得分:2)
你确实算到0,但行
print str(m.sqrt(i) - m.sqrt(i-1))
有i-1
,其中i == 0的计算结果为sqrt(-1)
答案 1 :(得分:1)
对于负整数使用cmath模块,它是python https://docs.python.org/2/library/cmath.html的内置模块
我希望这个答案可以帮助你:
import math as m,cmath
for i in range(10, -2, -1):
if i<=0:
print str(i) + ": " + str(cmath.sqrt(i))
print str(cmath.sqrt(i)-cmath.sqrt(i-1))
else:
print str(i) + ": " + str(m.sqrt(i))
print str(m.sqrt(i) - m.sqrt(i-1))
,输出结果为:
10: 3.16227766017
0.162277660168
9: 3.0
0.171572875254
8: 2.82842712475
0.182675813682
7: 2.64575131106
0.196261568281
6: 2.44948974278
0.213421765283
5: 2.2360679775
0.2360679775
4: 2.0
0.267949192431
3: 1.73205080757
0.317837245196
2: 1.41421356237
0.414213562373
1: 1.0
1.0
0: 0j
-1j
-1: 1j
-0.414213562373j