python实验

import numpy as np
import matplotlib.pyplot as plt

定义分段函数

def piecewise_function(x):
result = np.where(
np.logical_and(x >= -2, x <= 2), # 定义域 -2 <= x <= 2
np.where(
np.logical_or(x < 0, x > 1), # 第一部分的条件,这里假设原函数分段条件可能是 x 在非 [0,1] 区间为第一部分,你可根据实际修正
2 * np.sqrt(2 * np.abs(x**2 - x)),
-2.14 * np.sqrt(2 - np.sqrt(np.abs(x))) # 第二部分,对应 x 在 [0,1] 等情况,根据实际准确条件调整
),
0 # 定义域外返回 0,可根据需求调整
)
return result

生成 x 数据,在 -2 到 2 之间取足够多的点,使曲线平滑

x = np.linspace(-2, 2, 1000)

计算对应的 y 数据

y = piecewise_function(x)

绘制曲线

plt.plot(x, y, label='Piecewise Function', color='blue')

填充图形,这里填充曲线与 x 轴之间的区域,也可根据实际需求调整填充范围

plt.fill_between(x, y, 0, where=(y >= 0), color='lightblue', alpha=0.3)
plt.fill_between(x, y, 0, where=(y < 0), color='lightcoral', alpha=0.3)

添加标题和坐标轴标签

plt.title('Piecewise Function and Filled Area')
plt.xlabel('x')
plt.ylabel('y')

添加图例

plt.legend()

posted @ 2025-06-03 15:45  skurar  阅读(16)  评论(0)    收藏  举报