MathPHP\Functions\Polynomial::add PHP Метод

add() публичный Метод

Return a new polynomial that is the sum of the current polynomial and an input polynomial Example: $polynomial = new Polynomial([3, -16, 12]); // 3x² - 16x + 12 $integral = $polynomial->integrate(); // x³ - 8x² + 12x $sum = $polynomial->add($integral); // x³ - 5x² - 4x + 12
public add ( Polynomial $polynomial ) : Polynomial
$polynomial Polynomial The polynomial we are adding to our current polynomial
Результат Polynomial The sum of our polynomial objects, also a polynomial object
    public function add(Polynomial $polynomial) : Polynomial
    {
        // Calculate the degree of the sum of the polynomials
        $sumDegree = max($this->degree, $polynomial->degree);
        // Reverse the coefficients arrays so you can sum component-wise
        $coefficientsA = array_reverse($this->coefficients);
        $coefficientsB = array_reverse($polynomial->coefficients);
        // Start with an array of coefficients that all equal 0
        $sumCoefficients = array_fill(0, $sumDegree + 1, 0);
        // Iterate through each degree. Get coefficients by summing component-wise.
        for ($i = 0; $i < $sumDegree + 1; $i++) {
            // Calculate the degree of the current sum
            $degree = $sumDegree - $i;
            // Get the coefficient of the i-th degree term from each polynomial if it exists, otherwise use 0
            $a = $coefficientsA[$i] ?? 0;
            $b = $coefficientsB[$i] ?? 0;
            // The new coefficient is the sum of the original coefficients
            $sumCoefficients[$degree] = $sumCoefficients[$degree] + $a + $b;
        }
        return new Polynomial($sumCoefficients);
    }