整数除法错误

Errors with integer division

试图绘制一个函数,到目前为止我已经想出了这个。

import matplotlib.pyplot as plt R = 1.097e-2 for m in range(1,4): print("Series for m =",m) for n in range(m+1,m+6): invlambda = R*(1/m**2-1/n**2) print(" ",1/invlambda," nm")

我得到除以 0 的错误。不知道为什么...... 任何帮助将不胜感激。

问题是你在做整数除法。在 invlambda.

的定义中使用 1.
import matplotlib.pyplot as plt
R = 1.097e-2
for m in range(1,4):
     print("Series for m =",m)
     for n in range(m+1,m+6):
         invlambda = R*(1./m**2-1./n**2)
         print("  ",1/invlambda," nm")

在 python 2... 表达式 1/2 是一个整数除法并给出 1/2=0,因此你有 1/2**2-1/3**2=0。使用1.即可解决,即1./2 = 0.5.