[SOLVED] Python function that plots functions

Issue

I’m currently trying to define a function in python that plots functions.

I’ve already done this one:

def plota_f(x0, xf, n):
  xpoints = []
  ypoints = []
  for i in range(0,n):
      xpoints.append(x0+(xf-x0)/n *i)
      ypoints.append(np.sin(x0+(xf-x0)/n *i))
  plt.plot(xpoints, ypoints)
  plt.show()

that plots a Sin function from x0 to xf with n steps, but I would like to be able to add a parameter f

def plota_f(f,x0,xf,n):

so that I could call like

plota_f(x**2,0,10,100)

and plot a quadratic function or call

plota_f(np.sin(x),0,10,100)

and plot a sin function. Is there a simple way of doing that?


Edit: this is the code I got after the answer

def plota_f(f,x0,xf,n):
xpoints = []
ypoints = []
for i in range(0,n):
    xpoints.append(x0+(xf-x0)/n *i)
    x=x0+(xf-x0)/n *i
    ypoints.append(eval(f))
plt.plot(xpoints, ypoints)
plt.show()

Solution

It’s pretty easy with numpy:

from x0 to xf with n steps

This is the definition of np.linspace

be able to add a parameter f

Use a lambda function

Demo:

def plota_f(f, x0, xf, n):
    # Use with caution, eval can be dangerous
    xpoints = np.linspace(x0, xf, n, endpoint=True)
    ypoints = eval(f)
    plt.plot(xpoints, ypoints)
    plt.show()

plota_f('x**2', 0, 10, 100)

enter image description here

Answered By – Corralien

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published.