Plot Piecewise Function in Python

后端 未结 5 477
[愿得一人]
[愿得一人] 2021-01-02 10:56

I would like to plot the following piecewise function in Python using Matplotlib, from 0 to 5.

f(x) = 1, x != 2; f(x) = 0, x = 2

In Python...

5条回答
  •  青春惊慌失措
    2021-01-02 11:37

    You can use np.piecewise on the array:

    x = np.arange(0., 5., 0.2)
    import matplotlib.pyplot as plt
    plt.plot(x, np.piecewise(x, [x  == 2, x != 2], [0, 1]))
    

提交回复
热议问题