How to plot piecewise functions using Python

WBOY
Release: 2023-04-18 17:28:05
forward
3557 people have browsed it

The details are as follows:

How to plot piecewise functions using Python

How to draw the piecewise function as shown in the figure above in Python?

import matplotlib.pyplot as plt
import numpy as np
def f(x):
    if x <= -1:
        return -0.5 - x
    if -1 < x <= 1:
        return 0.5 * (x ** 2)
    else:
        return x - 0.5
x = np.linspace(-3, 3)
y = []
for i in x:
    y_1 = f(i)
    y.append(y_1)
plt.plot(x, y)
plt.grid()
plt.show()
Copy after login

How to plot piecewise functions using Python

Let’s change the example:

import matplotlib.pyplot as plt
import numpy as np
def f(x):
    if x <= -1:
        return 1
    if -1 < x <= 1:
        return 0.5 * (x ** 2)
    else:
        return 1
x = np.linspace(-3, 3)
y = []
for i in x:
    y_1 = f(i)
    y.append(y_1)
y_2 = x ** 2
plt.plot(x, y)
plt.grid()
plt.show()
Copy after login

The result is displayed as:

How to plot piecewise functions using Python

The above is the detailed content of How to plot piecewise functions using Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!