# Returning r at different theta values with numpy

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

I am easily able to graph and show the equation with matplotlib, and was hoping that there was an easy way to:

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

I tried to look at the documentation of numpy but am having a hard time finding what I need.

``````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()
``````

The above code produces a graph nicely, but:

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

On Best Solutions

It is in general not guaranteed that the array of theta values actually contains the value you want to query. As an example consider

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

Now you want to know the value of r at `theta0 = 2.5`, but since that value is not part of `theta` it has no corresponding value in `r`.

So you may decide to find the value of r at the theta that comes after `theta0`, in this case 3 is the next value in theta after 2.5, so you might be looking for r == 6,

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

Or you may want to interpolate the r values on theta, in this case 2.5 is halfway between 2 and 3, so you are looking for 6.5 which is halfway between 7 and 6,

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

Or more generally, you have an actual function, which defines `r(theta)`. Here,

``````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
``````

The last case for your example would look like

``````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()
``````