可以通过拉格朗日插值法来计算给定数据点的多项式插值,并且绘制出插值曲线。
<?php
// 多项式插值计算器
// 给定数据点
$dataPoints = [
[1, 3],
[2, 5],
[3, 2],
[4, 6]
];
// 拉格朗日插值函数
function lagrangeInterpolation($x, $dataPoints) {
$result = 0;
$n = count($dataPoints);
for ($i = 0; $i < $n; $i++) {
$term = $dataPoints[$i][1];
for ($j = 0; $j < $n; $j++) {
if ($j != $i) {
$term *= ($x - $dataPoints[$j][0]) / ($dataPoints[$i][0] - $dataPoints[$j][0]);
}
}
$result += $term;
}
return $result;
}
// 计算插值点
$interpolatedPoints = [];
for ($x = $dataPoints[0][0]; $x <= $dataPoints[count($dataPoints) - 1][0]; $x += 0.1) {
$y = lagrangeInterpolation($x, $dataPoints);
$interpolatedPoints[] = [$x, $y];
}
// 输出结果
echo "<h1>多项式插值结果</h1>";
echo "<p>给定数据点:</p>";
echo "<ul>";
foreach ($dataPoints as $point) {
echo "<li>($point[0], $point[1])</li>";
}
echo "</ul>";
// 绘制插值曲线
echo "<h2>插值曲线</h2>";
echo "<svg width='400' height='200'>";
echo "<polyline points='";
foreach ($interpolatedPoints as $point) {
echo $point[0] * 20 . "," . (100 - $point[1] * 10) . " ";
}
echo "' style='fill:none;stroke:black;stroke-width:2'/>";
echo "</svg>";
?>