为了账号安全,请及时绑定邮箱和手机立即绑定

使用 numpy 以不同的 theta 值返回 r

使用 numpy 以不同的 theta 值返回 r

皈依舞 2022-01-18 13:49:08
我需要根据 r 在不同的 theta 值处等于什么来生成一个表。我可以很容易地用 matplotlib 绘制和显示方程,并希望有一种简单的方法:给 numpy theta 变量、我的曲线方程和 viola,返回 r 值我试图查看 numpy 的文档,但很难找到我需要的东西。import matplotlib.pyplot as pltimport matplotlib as mplimport numpy as npmpl.style.use('default')# Number of Points Ploted# Change this numer to affect accuracy of the graphn = 3000theta = np.linspace(0, 2.0*np.pi, n)def show_grid():  plt.grid(True)  plt.legend()  plt.show()# Setting the range of theta to [0, 2π] for this specific equationtheta4 = np.linspace(0, 2*np.pi, n)# Writing the equationcurve4 = 5*np.cos(64*theta)ax1 = plt.subplot(111, polar=True)ax1.plot(theta4, curve4, color='xkcd:cyan', label='CURVE 4: r = 5cos(64θ), [0, 2π)')ax1.set_ylim(0,5)ax1.set_yticks(np.linspace(0,5,6))show_grid()上面的代码很好地生成了一个图表,但是:我可以使用相同的变量在 theta 处返回 r 吗?
查看完整描述

1 回答

?
HUWWW

TA贡献1874条经验 获得超12个赞

通常不能保证 theta 值数组实际上包含您要查询的值。作为一个例子考虑


theta = np.array([1,2,3,4])

r = np.array([8,7,6,5])

现在您想知道 r at 的值theta0 = 2.5,但由于该值不是它的一部分,theta因此在 中没有对应的值r。


因此,您可能决定在 之后的 theta 处找到 r 的值theta0,在这种情况下,3 是 2.5 之后 theta 中的下一个值,因此您可能正在寻找 r == 6,


theta0 = 2.5

print(r[np.searchsorted(theta, theta0)])   # prints 6

或者您可能想要在 theta 上插入 r 值,在这种情况下,2.5 介于 2 和 3 之间,因此您正在寻找 6.5,它介于 7 和 6 之间,


theta0 = 2.5

print(np.interp(theta0, theta, r))    # prints 6.5

或者更一般地说,你有一个实际的函数,它定义了r(theta). 这里,


theta = np.array([1,2,3,4])

rf = lambda x: -x + 9


r = rf(theta)

print(r)                              # prints [8,7,6,5]


print(rf(theta0))                     # prints 6.5

您的示例的最后一个案例看起来像


theta = np.linspace(0, 2*np.pi, 3001)


# Writing the equation

r = lambda theta: 5*np.cos(64*theta)


ax1 = plt.subplot(111, polar=True)

ax1.plot(theta, r(theta), label='CURVE 4: r = 5cos(64θ), [0, 2π)')


print(r(np.pi/2))  # prints 5


plt.show()


查看完整回答
反对 回复 2022-01-18
  • 1 回答
  • 0 关注
  • 200 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号