Home > Net >  Python function that plots functions
Python function that plots functions

Time:02-04

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?

CodePudding user response:

You are over-complicating the problem. Here is how I would plot a sine function with frequency f over some interval, say from t0 to t1 with n steps:

t = np.linspace(t0, t1, n)
fn = np.sin(2 * np.pi * f * t)
plt.plot(t, fn)

When you separate out the domain vs function values, you can see a path forward. For example, you could define a function like this:

def my_sin(f):
    def func(t):
        return np.sin(2 * np.pi * f * t)
    return func

Now you can do something like this now:

def plot_func(func, t0, t1, n):
    t = np.linspace(t0, t1, n)
    plt.plot(t, func(t))

You just have to define functions that accept a single parameter t, which is an array of the points you want to evaluate at:

def my_quad(a, b, c):
    def func(t):
        return a * t**2   b * t   c
    return func

plot_func(my_sin(10), -10, 10, 1000)
plot_func(my_quad(3, 0, 0), -5, 5, 100)

CodePudding user response:

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

  •  Tags:  
  • Related