You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在步长0.01的(-4,4)区间内绘制3个指定分段函数的图像

分段函数绘制实现方案

你可以根据自己常用的环境选择对应代码,均已适配你要求的(-4,4)区间、0.01步长,且严格匹配你给出的分段函数逻辑:


方案1:Python + Matplotlib 实现

import numpy as np
import matplotlib.pyplot as plt

# 生成符合要求的x序列
x = np.arange(-4, 4, 0.01)

# 计算PieceWise1
y1 = np.where(
    x <= 0,
    2 + np.sqrt(4 - (x + 2)**2),
    -0.5 * x
)

# 计算PieceWise2
y2 = np.where(
    x <= 0,
    2 - np.sqrt(4 - (x + 2)**2),
    0.5 * x - 4
)

# 计算PieceWise3
def calc_y3(x_val):
    if x_val < -0.12:
        return -4 - 1/(2 * x_val)
    elif x_val >= 0:
        z = x_val - 2 * np.floor(x_val / 2)
        return 4 * (1 - z)**2
    else:
        return 0
calc_y3_vec = np.vectorize(calc_y3)
y3 = calc_y3_vec(x)

# 绘图
plt.figure(figsize=(10,6))
plt.plot(x, y1, label='PieceWise1', color='#FF5733')
plt.plot(x, y2, label='PieceWise2', color='#33A1FF')
plt.plot(x, y3, label='PieceWise3', color='#33FF57')
plt.xlabel('x')
plt.ylabel('y')
plt.legend()
plt.grid(alpha=0.3)
plt.show()

代码说明:用np.vectorize适配第三个函数的多分支逻辑,避免逐点循环的冗余,运行后直接输出三个函数的对比图像。


方案2:Scilab 实现(匹配你给出的函数语法环境)

你给出的函数是Scilab语法,直接用以下代码就能运行:

// 生成x序列
x = -4:0.01:4;
len = length(x);
y1 = zeros(1, len);
y2 = zeros(1, len);
y3 = zeros(1, len);

// 计算PieceWise1和PieceWise2的x<=0部分
ind_le0 = x <= 0;
root = sqrt(4 - (x(ind_le0) + 2).^2);
y1(ind_le0) = 2 + root;
y2(ind_le0) = 2 - root;
// 计算x>0部分
ind_gt0 = x > 0;
y1(ind_gt0) = -0.5 * x(ind_gt0);
y2(ind_gt0) = 0.5 * x(ind_gt0) - 4;

// 计算PieceWise3
ind_lt_neg012 = x < -0.12;
ind_ge0 = x >= 0;
y3(ind_lt_neg012) = -4 - 1 ./ (2 * x(ind_lt_neg012));
z = x(ind_ge0) - 2 * int(x(ind_ge0)/2);
y3(ind_ge0) = 4 * (1 - z).^2;
// 中间-0.12<=x<0部分默认是0,不用额外赋值

// 绘图
plot(x, y1, 'r', x, y2, 'b', x, y3, 'g')
legend('PieceWise1', 'PieceWise2', 'PieceWise3')
xgrid

内容的提问来源于stack exchange,提问作者Ushani Bandara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 23:27:02