operator / method
Divide operator. Creates a Divide expression.
Throws ExpressionOperationException if the operand cannot be converted to an Expression.
Implementation
@override
Expression operator /(dynamic other) {
if (other is Polynomial) {
// Check for zero polynomial
if (other.coefficients.isEmpty ||
(other.coefficients.first is Literal &&
(other.coefficients.first as Literal).value == Complex.zero())) {
throw Exception('Division by zero polynomial.');
}
List<Expression> dividendCoeffs = _trimLeadingZeros(coefficients);
List<Expression> divisorCoeffs = _trimLeadingZeros(other.coefficients);
int dividendDegree = dividendCoeffs.length - 1;
int divisorDegree = divisorCoeffs.length - 1;
if (divisorDegree > dividendDegree) {
return Add(Polynomial([Literal(0)]), RationalFunction(this, other));
}
List<Expression> quotientCoeffs =
List.filled(dividendDegree - divisorDegree + 1, Literal(0));
for (int k = 0; k <= dividendDegree - divisorDegree; k++) {
// quotient[k] = dividend[k] / divisor[0]
quotientCoeffs[k] =
Divide(dividendCoeffs[k], divisorCoeffs[0]).simplifyBasic();
for (int j = 0; j <= divisorDegree; j++) {
// dividend[k+j] -= quotient[k] * divisor[j]
dividendCoeffs[k + j] = Subtract(dividendCoeffs[k + j],
Multiply(quotientCoeffs[k], divisorCoeffs[j]))
.simplifyBasic();
}
}
// Correcting the range of indices for the remainder coefficients
List<Expression> remainderCoeffs =
dividendCoeffs.sublist(dividendDegree - divisorDegree + 1);
return Add(
Polynomial(_trimLeadingZeros(quotientCoeffs), variable: variable),
RationalFunction(
Polynomial(_trimLeadingZeros(remainderCoeffs), variable: variable),
other),
);
}
return Divide(this, other);
}