private static function factorialSerie(Decimal $x, Decimal $firstTerm, callable $generalTerm, $scale)
{
$approx = $firstTerm;
$change = InfiniteDecimal::getPositiveInfinite();
$faculty = DecimalConstants::One();
// Calculates the faculty under the sign
$xPowerN = DecimalConstants::One();
// Calculates x^n
for ($i = 1; !$change->floor($scale + 1)->isZero(); $i++) {
// update x^n and n! for this walkthrough
$xPowerN = $xPowerN->mul($x);
$faculty = $faculty->mul(Decimal::fromInteger($i));
$multiplier = $generalTerm($i);
if (!$multiplier->isZero()) {
$change = $multiplier->mul($xPowerN, $scale + 2)->div($faculty, $scale + 2);
$approx = $approx->add($change, $scale + 2);
}
}
return $approx->round($scale);
}