首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 實現 Lagrange 插值算法:從數學原理到圖像繪製

     編輯:PHP 相關知識

數學原理速覽

給定 n 個已知點 (x₀,y₀)…(xₙ₋₁,yₙ₋₁),Lagrange 插值構造 n-1 次多項式:

f(x) = Σₖ₌₀ⁿ⁻¹ yₖ · Lₖ(x)

其中基函數 Lₖ(x) = Πᵢ₌₀,ᵢ≠ₖⁿ⁻¹ (x - xᵢ) / (xₖ - xᵢ)。

PHP 類實現

<?php
class Lagrange {
    private $dots = [];

    public function __construct(array $dots) {
        // $dots = ['x' => [...], 'y' => [...]]
        $this->dots = $dots;
    }

    private function getLk(float $x, int $k): float {
        $n = count($this->dots['x']);
        $omega_xk = 1.0;
        $omega_x  = 1.0;
        for ($i = 0; $i < $n; $i++) {
            if ($i !== $k) {
                $omega_xk *= ($this->dots['x'][$k] - $this->dots['x'][$i]);
                $omega_x  *= ($x - $this->dots['x'][$i]);
            }
        }
        return $omega_x / $omega_xk;
    }

    public function getY(float $x): float {
        $n = count($this->dots['x']);
        $sum = 0.0;
        for ($k = 0; $k < $n; $k++) {
            $sum += $this->dots['y'][$k] * $this->getLk($x, $k);
        }
        return $sum;
    }

    public function draw(): void {
        $img = imagecreatetruecolor(500, 500);
        $white = imagecolorallocate($img, 255, 255, 255);
        $black = imagecolorallocate($img, 0, 0, 0);
        $red   = imagecolorallocate($img, 255, 0, 0);
        imagefill($img, 0, 0, $white);

        $n = count($this->dots['x']);
        $maxX = max($this->dots['x']);
        $step = 0.1;
        $r = 4;

        // 繪製已知點
        for ($i = 0; $i < $n; $i++) {
            $px = (int)$this->dots['x'][$i];
            $py = 500 - (int)$this->dots['y'][$i]; // Y 軸翻轉
            imagefilledellipse($img, $px, $py, $r, $r, $red);
        }

        // 繪製插值曲線
        for ($x = $this->dots['x'][0] - 10; $x < $maxX + 10; $x += $step) {
            $x1 = (int)$x;
            $y1 = 500 - (int)$this->getY($x);
            $x2 = (int)($x + $step);
            $y2 = 500 - (int)$this->getY($x + $step);
            imageline($img, $x1, $y1, $x2, $y2, $black);
        }

        header('Content-Type: image/png');
        imagepng($img);
        imagedestroy($img);
    }
}

// 使用示例
$points = [
    'x' => [10, 30, 100, 120, 220],
    'y' => [20, 40, 240, 220, 340],
];
$lag = new Lagrange($points);
$lag->draw();

關鍵點說明

  1. 坐標系轉換:GD 庫原點在左上角,Y 軸向下;數學坐標 Y 軸向上,繪圖時需 500 - y 翻轉。
  2. 步長選擇:$step = 0.1 平衡曲線平滑度與性能;生產環境可根據圖像寬度動態計算。
  3. 數值穩定性:當 xᵢ 接近時分母極小,易產生數值震盪。工程上可改用 牛頓插值 或 樣條插值。

擴展方向

  • 輸出 SVG/Canvas 供前端交互縮放。
  • 增加 getPolynomialCoefficients() 導出多項式系數,便於離線計算。
  • 結合 gnuplot 或 Python Matplotlib 生成出版級圖表。

總結

Lagrange 插值原理直觀、實現簡潔,適合教學演示與小規模數據擬合。PHP 配合 GD 庫可直觀輸出圖像,但大規模或高精度場景建議轉向 SciPy/NumPy 生態。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved