圆形图形程序空值错误(Python 3.4)

时间:2014-07-07 21:04:17

标签: python numpy matplotlib

这是我根据用户输入的半径和中心坐标绘制圆圈的程序。

import numpy as np
import matplotlib.pyplot as plt
def circle(r,h,k,domain):
    x = np.array(domain)
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
    plt.plot(x,y)
    plt.show
rad = float(input("Radius: "))
xcen = float(input("Center X Coordinate: "))
ycen = float(input("Center Y Coordinate: "))

circle(rad,xcen,ycen,np.linspace(-10,10,500))
print("Done")

运行时我会收到这些错误。

Warning (from warnings module):
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 5
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
RuntimeWarning: invalid value encountered in sqrt
Traceback (most recent call last):
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 13, in <module>
    circle(rad,xcen,ycen,np.linspace(-10,10,500))
  File "/Users/William/Documents/Science/PYTHON3/Circle.py", line 5, in circle
    y = eval(np.sqrt(r**2 - (x-h)**2) + k)
TypeError: source code string cannot contain null bytes

1 个答案:

答案 0 :(得分:0)

eval不用于python中的算术评估,只需将其从

中删除即可
y = eval(np.sqrt(r**2 - (x-h)**2) + k)

获取有效的

y = np.sqrt(r**2 - (x-h)**2) + k

同时将每个点绘制为单独的数据系列是一个坏主意,你应该创建x和y的列表然后运行。

plt.scatter(X,Y) # plt.plot() is used for line plots, not point plots
plt.show() # plt.show is the reference to the function, you need () to call it