Skip to content

Instantly share code, notes, and snippets.

@JordanRL
Last active August 11, 2021 09:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JordanRL/98cceb392ba5ba943462fe574f18de51 to your computer and use it in GitHub Desktop.
Save JordanRL/98cceb392ba5ba943462fe574f18de51 to your computer and use it in GitHub Desktop.
Complex number multiply
<?php
public function multiply($num)
{
[
$thatRealPart,
$thatImaginaryPart,
$thisRealPart,
$thisImaginaryPart,
$num
] = $this->translateToParts($this, $num, 1);
if ($num->isComplex()) {
$foiled = PolynomialFunction::createFromFoil([
$thisRealPart,
$thisImaginaryPart
], [
$thatRealPart,
$thatImaginaryPart
]);
$parts = $foiled->describeShape();
$newRealPart = new ImmutableDecimal($parts[0]);
$newImaginaryPart = new ImmutableDecimal($parts[1]);
/** @var ImmutableDecimal $newRealPart */
$newRealPart = $newRealPart->add($parts[2]);
} else {
$value1 = $thisRealPart->multiply($num);
$value2 = $thisImaginaryPart->multiply($num);
$newRealPart = $value1->isReal() ? $value1 : $value2;
$newImaginaryPart = $value1->isImaginary() ? $value1 : $value2;
}
if (!$newRealPart->isEqual(0) && !$newImaginaryPart->isEqual(0)) {
return $this->setValue($newRealPart, $newImaginaryPart);
}
$value = $newRealPart->isEqual(0) ? $newImaginaryPart : $newRealPart;
return new ImmutableDecimal($value->getValue());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment