graphing an equation with matplotlib

前端 未结 3 1608
孤城傲影
孤城傲影 2021-01-30 10:54

I\'m trying to make a function that will graph whatever formula I tell it to.

import numpy as np  
import matplotlib.pyplot as plt  
def graph(formula, x_range):         


        
3条回答
  •  广开言路
    2021-01-30 11:42

    Your guess is right: the code is trying to evaluate x**3+2*x-4 immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do:

    import numpy as np  
    import matplotlib.pyplot as plt  
    
    def graph(formula, x_range):  
        x = np.array(x_range)  
        y = formula(x)  # <- note now we're calling the function 'formula' with x
        plt.plot(x, y)  
        plt.show()  
    
    def my_formula(x):
        return x**3+2*x-4
    
    graph(my_formula, range(-10, 11))
    

    If you wanted to do it all in one line, you could use what's called a lambda function, which is just a short function without a name where you don't use def or return:

    graph(lambda x: x**3+2*x-4, range(-10, 11))
    

    And instead of range, you can look at np.arange (which allows for non-integer increments), and np.linspace, which allows you to specify the start, stop, and the number of points to use.

提交回复
热议问题