猿问

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

我需要根据 r 在不同的 theta 值处等于什么来生成一个表。

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


给 numpy theta 变量、我的曲线方程和 viola,返回 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 吗?


皈依舞
浏览 217回答 1
1回答

HUWWW

通常不能保证 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.5print(r[np.searchsorted(theta, theta0)])   # prints 6或者您可能想要在 theta 上插入 r 值,在这种情况下,2.5 介于 2 和 3 之间,因此您正在寻找 6.5,它介于 7 和 6 之间,theta0 = 2.5print(np.interp(theta0, theta, r))    # prints 6.5或者更一般地说,你有一个实际的函数,它定义了r(theta). 这里,theta = np.array([1,2,3,4])rf = lambda x: -x + 9r = 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 equationr = 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 5plt.show()
随时随地看视频慕课网APP

相关分类

Python
我要回答