Last active
August 29, 2015 14:15
-
-
Save maxbucknell/0834ea3840adbc499965 to your computer and use it in GitHub Desktop.
Really short and crappy complex number implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class ComplexNumber { | |
private $real; | |
private $imaginary; | |
public function __construct($real, $imaginary) { | |
$this->real = $real; | |
$this->imaginary = $imaginary; | |
} | |
public function __toString() { | |
return $real . ' + ' . $imaginary . 'i'; | |
} | |
public function getReal() { | |
return $this->real; | |
} | |
public function getImaginary() { | |
return $this->imaginary; | |
} | |
public function getConjugate() { | |
$real = $this->getReal(); | |
$imaginary = -$this->getImaginary(); | |
return new ComplexNumber($real, $imaginary); | |
} | |
public function getMagnitude() { | |
$product = $this->multiply($this->getConjugate()); | |
$float = $product->getReal(); | |
return sqrt($float); | |
} | |
public function getArgument() { | |
// Complex stuff | |
return pi() / 2; | |
} | |
public function add(ComplexNumber other) { | |
$real = $this->getReal() + $other->getReal(); | |
$imaginary = $this->getImaginary + $other->getImaginary(); | |
return new ComplexNumber($real, $imaginary); | |
} | |
public function multiply(ComplexNumber $other) { | |
$real = $this->getReal() * $other->getReal() - | |
$this->getImaginary() * $other->getImaginary(); | |
$imaginary = $this->getReal() * $other->getImaginary() + | |
$this>getImaginary() * $other->getReal(); | |
return new ComplexNumber($real, $imaginary); | |
} | |
public function subtract(ComplexNumber $other) { | |
$factor = new ComplexNumber(-1, 0); | |
return $this->add($other->multiply($factor)); | |
} | |
public function divide(ComplexNumber $other) { | |
$numerator = $this->multiply($other->getConjugate(); | |
$denominator = ComplexNumber(1 / $other->getMagnitude(), 0); | |
return $numerator->multiply($denominator); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment