我是新来的Python,特别是初次使用matplotlib绘制图表。我工作的一个任务,我们必须绘制与方程x和y直角坐标系上万花尺:
x = (R + r) * math.cos(theta) - d * math.cos((R+r)*theta/r)
y = (R + r) * math.sin(theta) - d * math.sin((R+r)*theta/r)
在这里我们给出R,r和d的值。
因为变量THETA没有定义该产生错误。我见过定义使用numpy的theta的方式,但我们不会允许使用特定库这项任务。什么是绘制0 <THETA <二皮的万花尺的最佳方式?
提前致谢!
如果你不能使用numpy的,你不能使用matplotlib;因为numpy的是matplotlib的依赖。所以,我建议解决下列方式您的问题:
前面加上一个句子到解决方案中说:“由于numpy的是matplotlib的依赖,这在技术上是不可能解决这个任务,而无需使用numpy的。因为我不希望这个限制阻止我解决的任务,我只是认为我可以用numpy的这里。”
然后继续用典型的解决方案,
import matplotlib.pyplot as plt
import numpy as np
theta = np.linspace(0,2*np.pi,301)
R = 8
r = 1
d = 3
x = (R + r) * np.cos(theta) - d * np.cos((R+r)*theta/r)
y = (R + r) * np.sin(theta) - d * np.sin((R+r)*theta/r)
plt.plot(x,y)
plt.axis("equal")
plt.show()
如果你不能使用numpy的,你可以用功能和循环做到这一点:
import math
import matplotlib.pyplot as plt
def X(theta,R,r,d) :
return (R + r) * math.cos(theta) - d * math.cos((R+r)*theta/r)
def Y(theta,R,r,d) :
return (R + r) * math.sin(theta) - d * math.sin((R+r)*theta/r)
nbSamples=100
theta=[]
for i in range (nbSamples) :
theta.append(i/(nbSamples-1)*2*math.pi)
x=[]
y=[]
R=8
r=1
d=3
for th in theta:
x.append(X(th,R,r,d))
y.append(Y(th,R,r,d))
plt.plot(x,y)
plt.axis("equal")
plt.show()