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

approximate() public static method

The bounds of the definite integral to which we are approximating is determined by the our inputs. Example: approximate([0, 10], [3, 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. Trapezoidal Rule: xn ⁿ⁻¹ xᵢ₊₁ ∫ f(x)dx = ∑ ∫ f(x)dx x₁ ⁱ⁼¹ xᵢ ⁿ⁻¹ h = ∑ - [f(xᵢ₊₁) + f(xᵢ)] + O(h³f″(x)) ⁱ⁼¹ 2 where h = xᵢ₊₁ - xᵢ note: this implementation does not compute the error term.
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 = 2);
        $sorted = self::sort($points);
        // Descriptive constants
        $x = self::X;
        $y = self::Y;
        // Initialize
        $n = count($sorted);
        $steps = $n - 1;
        $approximation = 0;
        /*
         * Summation
         * ⁿ⁻¹  h
         *  ∑   - [f(xᵢ₊₁) + f(xᵢ)]
         * ⁱ⁼¹  2
         *  where h = xᵢ₊₁ - xᵢ
         */
        for ($i = 0; $i < $steps; $i++) {
            $xᵢ = $sorted[$i][$x];
            $xᵢ₊₁ = $sorted[$i + 1][$x];
            $f⟮xᵢ⟯ = $sorted[$i][$y];
            // yᵢ
            $f⟮xᵢ₊₁⟯ = $sorted[$i + 1][$y];
            // yᵢ₊₁
            $lagrange = LagrangePolynomial::interpolate([[$xᵢ, $f⟮xᵢ⟯], [$xᵢ₊₁, $f⟮xᵢ₊₁⟯]]);
            $integral = $lagrange->integrate();
            $approximation += $integral($xᵢ₊₁) - $integral($xᵢ);
            // definite integral of lagrange polynomial
        }
        return $approximation;
    }
TrapezoidalRule