用numpy返回不同theta值的r

问题描述 投票:0回答:1

I need to generate a table based on what r equals at different theta values.

我很容易用matplotlib绘制并显示方程式,并希望有一种简单的方法:

给ntay theta变量,我的曲线方程和中提琴,返回r值

我试着看看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()

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

我可以使用相同的变量在theta处返回r吗?

python numpy matplotlib polar-coordinates
1个回答
0
投票

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

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

现在你想知道q在theta0 = 2.5的值,但由于这个值不是theta的一部分,它在r中没有相应的值。

因此,您可能决定在theta0之后的theta处找到r的值,在这种情况下,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()
© www.soinside.com 2019 - 2024. All rights reserved.