user405381
user405381

Reputation: 37

Plotting defined function

I've defined a function which I would now like to plot:

import numpy as np
from math import pi, sqrt
import matplotlib.pyplot as plt

def f(x: float) -> float:
    return pi * x * sqrt(x**2 + 400) + pi * x**2 - 1200

plt.plot(f(x))
plt.show()

When running this code, I get "NameError: name 'x' is not defined".

Upvotes: 0

Views: 3852

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339052

It is often usefull to use numpy in conjunction with matplotlib. When you then define a function, you may write it such that it takes single floats as well as numpy arrays as input.

import numpy as np
import matplotlib.pyplot as plt

def f(x):
    return np.pi * x * np.sqrt(x**2 + 400) + np.pi * x**2 - 1200

x = np.array([1,2,3,4])
plt.plot(x, f(x))
plt.show()

Of course you could now also evaluate the function for a single float

print( f(9.2) )

or use it for each element of a list or array

y = [f(i) for i in x]
plt.plot(x,y)

But once you know about the fact that mathematical operations can be applied to numpy arrays easily, you probably don't want to opt for the latter anymore.

Upvotes: 4

Related Questions