Skip to content

Instantly share code, notes, and snippets.

@maxbucknell
Last active August 29, 2015 14:15
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 maxbucknell/0834ea3840adbc499965 to your computer and use it in GitHub Desktop.
Save maxbucknell/0834ea3840adbc499965 to your computer and use it in GitHub Desktop.
Really short and crappy complex number implementation
<?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