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

Returning r at different theta values with numpy

我需要根据 r 在不同 theta 值下的相等值生成 table。

我可以轻松地使用 matplotlib 绘制和显示方程式,并希望有一种简单的方法可以:

give numpy the theta variable, my curve equation, and viola, return the r value

我试图查看 numpy 的文档,但很难找到我需要的东西。

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np

mpl.style.use('default')

# Number of Points Ploted
# Change this numer to affect accuracy of the graph
n = 3000

theta = 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 equation
theta4 = np.linspace(0, 2*np.pi, n)

# Writing the equation
curve4 = 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()

上面的代码很好地生成了一个图表,但是:

Can I use the same variables to return r at theta?

一般不保证theta值数组中确实包含您要查询的值。例如考虑

theta = np.array([1,2,3,4])
r = np.array([8,7,6,5])

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

因此您可能决定在 theta0 之后的 theta 处找到 r 的值,在这种情况下,3 是 theta 中 2.5 之后的下一个值,因此您可能正在寻找 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()