MathPHP\NumericalAnalysis\NumericalIntegration\SimpsonsRule::approximate PHP Method

approximate() public static method

Note: Simpson's method requires that we have an even number of subintervals (we must supply an odd number of points) and also that the size of each subinterval is equal (spacing between each point is equal). The bounds of the definite integral to which we are approximating is determined by the our inputs. Example: approximate([0, 10], [5, 5], [10, 7]) will approximate the definite integral of the function that produces these coordinates with a lower bound of 0, and an upper bound of 10. Example: approximate(function($x) {return $x**2;}, 0, 4 ,5) will produce a set of arrays by evaluating the callback at 5 evenly spaced points between 0 and 4. Then, this array will be used in our approximation. Simpson's Rule: xn ⁿ⁻¹ xᵢ₊₁ ∫ f(x)dx = ∑ ∫ f(x)dx x₁ ⁱ⁼¹ xᵢ ⁽ⁿ⁻¹⁾/² h = ∑ - [f⟮x₂ᵢ₋₁⟯ + 4f⟮x₂ᵢ⟯ + f⟮x₂ᵢ₊₁⟯] + O(h⁵f⁗(x)) ⁱ⁼¹ 3 where h = (xn - x₁) / (n - 1)
public static approximate ( $source, $args ) : number
$source The source of our approximation. Should be either a callback function or a set of arrays. Each array (point) contains precisely two numbers, an x and y. Example array: [[1,2], [2,3], [3,4]]. Example callback: function($x) {return $x**2;}
return number The approximation to the integral of f(x)
    public static function approximate($source, ...$args)
    {
        // get an array of points from our $source argument
        $points = self::getPoints($source, $args);
        // Validate input and sort points
        self::validate($points, $degree = 3);
        Validation::isSubintervalsMultiple($points, $m = 2);
        $sorted = self::sort($points);
        Validation::isSpacingConstant($sorted);
        // Descriptive constants
        $x = self::X;
        $y = self::Y;
        // Initialize
        $n = count($sorted);
        $subintervals = $n - 1;
        $a = $sorted[0][$x];
        $b = $sorted[$n - 1][$x];
        $h = ($b - $a) / $subintervals;
        $approximation = 0;
        /*
         * Summation
         * ⁽ⁿ⁻¹⁾/² h
         *    ∑    - [f⟮x₂ᵢ₋₁⟯ + 4f⟮x₂ᵢ⟯ + f⟮x₂ᵢ₊₁⟯] + O(h⁵f⁗(x))
         *   ⁱ⁼¹   3
         *  where h = (xn - x₁) / (n - 1)
         */
        for ($i = 1; $i < $subintervals / 2 + 1; $i++) {
            $x₂ᵢ₋₁ = $sorted[2 * $i - 2][$x];
            $x₂ᵢ = $sorted[2 * $i - 1][$x];
            $x₂ᵢ₊₁ = $sorted[2 * $i][$x];
            $f⟮x₂ᵢ₋₁⟯ = $sorted[2 * $i - 2][$y];
            // y₂ᵢ₋₁
            $f⟮x₂ᵢ⟯ = $sorted[2 * $i - 1][$y];
            // y₂ᵢ
            $f⟮x₂ᵢ₊₁⟯ = $sorted[2 * $i][$y];
            // y₂ᵢ₊₁
            $lagrange = LagrangePolynomial::interpolate([[$x₂ᵢ₋₁, $f⟮x₂ᵢ₋₁⟯], [$x₂ᵢ, $f⟮x₂ᵢ⟯], [$x₂ᵢ₊₁, $f⟮x₂ᵢ₊₁⟯]]);
            $integral = $lagrange->integrate();
            $approximation += $integral($x₂ᵢ₊₁) - $integral($x₂ᵢ₋₁);
            // definite integral of lagrange polynomial
        }
        return $approximation;
    }
SimpsonsRule