0

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".

1
  • 1
    You need to initialize x with some value Commented Sep 28, 2017 at 10:04

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.