基于 function-plot.js 开源库绘制数学函数图像实现兼文档翻译_wx64649997c45fd的技术博客_51CTO博客
image.png
image.png
image.png
通用模型
image.png
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Arbitrary-Order Step Response with Delay</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/10.0.0/math.min.js"></script>
<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
</head>
<body>
<div id="plot" style="width:100%;height:500px;"></div>
<script>
// 定义传递函数系数
const numerator = [1]; // 分子系数 [b0, b1, ..., bm]
const denominator = [1, 2, 2]; // 分母系数 [a0, a1, ..., an]
const theta = 5; // 延时
// 定义时间范围
const t = Array.from({ length: 500 }, (_, i) => i * 0.1); // 从 0 到 50,步长 0.1
// 定义拉普拉斯逆变换(数值方法)
function inverseLaplace(Y, t) {
const y = [];
for (let i = 0; i < t.length; i++) {
const ti = t[i];
let sum = 0;
for (let j = 0; j < 1000; j++) {
const s = math.complex(0.1 * j, 0); // 沿实轴积分
const Ys = Y(s);
sum += math.multiply(Ys, math.exp(math.multiply(s, ti))).re;
}
y.push(sum * 0.1); // 积分步长
}
return y;
}
// 定义传递函数 Y(s) = H(s) / s
function Y(s) {
const num = numerator.reduce((acc, coeff, idx) =>
math.add(acc, math.multiply(coeff, math.pow(s, idx))), math.complex(0, 0));
const den = denominator.reduce((acc, coeff, idx) =>
math.add(acc, math.multiply(coeff, math.pow(s, idx))), math.complex(0, 0));
return math.divide(math.divide(num, den), s);
}
// 计算无延时的阶跃响应
const y0 = inverseLaplace(Y, t);
// 增加延时
const y = t.map((ti, i) => (ti >= theta) ? y0[i - Math.floor(theta / 0.1)] : 0);
// 使用 Plotly 绘图
const trace = {
x: t,
y: y,
type: 'scatter',
mode: 'lines',
name: 'Step Response',
line: { color: 'blue' },
};
const layout = {
title: 'Unit Step Response with Delay',
xaxis: { title: 'Time (t)' },
yaxis: { title: 'Output (y(t))' },
showlegend: true,
};
Plotly.newPlot('plot', [trace], layout);
</script>
</body>
</html>