Skip to content

Commit

Permalink
add modulus method to complex type
Browse files Browse the repository at this point in the history
  • Loading branch information
akitson-fu committed Jul 26, 2014
1 parent ee375b3 commit 3c6367b
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
5 changes: 4 additions & 1 deletion README.md
Expand Up @@ -151,9 +151,10 @@ Complex numbers support some additional attributes:
* isZero(): r() == i() == 0
* isGaussian(): is_int(r()) && is_int(i())

and a method
and two methods

* conjugate(): returns conjugate of the complex number
* modulus(): returns the modulus, also known as absolute value or magnitude of the complex number

### Changing the library

Expand Down Expand Up @@ -219,3 +220,5 @@ V1.0.1 Remove requirement for zendfilter package to reduce dependency footprint
V1.0.2 Add conjugate method to complex type

rebase wholeInt and naturalInt type on intType

V1.0.3 Add modulus method to complex type
10 changes: 10 additions & 0 deletions src/chippyash/Type/Number/Complex/ComplexType.php
Expand Up @@ -90,6 +90,16 @@ public function conjugate()
return new self(new FloatType($this->real), new FloatType($this->imaginary * -1));
}

/**
* Return the modulus, also known as absolute value or magnitude of this number
*
* @return \chippyash\Type\Number\FloatType
*/
public function modulus()
{
return new FloatType(sqrt(pow($this->real, 2)+pow($this->imaginary, 2)));
}

/**
* Proxy to get()
*
Expand Down
32 changes: 32 additions & 0 deletions test/src/chippyash/Type/Number/Complex/ComplexTypeTest.php
Expand Up @@ -148,4 +148,36 @@ public function testIsGaussianForOnePartNotBeingIntegerValuesReturnsFalse()
$c2 = new ComplexType(new FloatType(1), new FloatType(2.000001));
$this->assertFalse($c2->isGaussian());
}

public function testModulusForZeroComplexNumberIsZero()
{
$c = new ComplexType(new FloatType(0), new FloatType(0));
$this->assertEquals(0, $c->modulus()->get());
}

public function testTriangleInequalityForModulus()
{
$c1 = new ComplexType(new FloatType(1), new FloatType(2));
$c2 = new ComplexType(new FloatType(3), new FloatType(4));
$c1addc2 = new ComplexType(new FloatType($c1->r() + $c2->r()), new FloatType($c1->i() + $c2->i()));
$mod1 = $c1->modulus();
$mod2 = $c2->modulus();
$modc1addc2 = $c1addc2->modulus();

$this->assertTrue($modc1addc2() <= ($mod1() + $mod2()));
}

public function testCommutativeMultiplicationAttributeForModulus()
{
$c1 = new ComplexType(new FloatType(1), new FloatType(2));
$c2 = new ComplexType(new FloatType(3), new FloatType(4));
$c1mulc2 = new ComplexType(
new FloatType(($c1->r() * $c2->r()) - ($c1->i() * $c2->i())),
new FloatType(($c1->i() * $c2->r()) + ($c1->r() * $c2->i())));
$mod1 = $c1->modulus();
$mod2 = $c2->modulus();
$modc1mulc2 = $c1mulc2->modulus();

$this->assertEquals($modc1mulc2(), $mod1() * $mod2());
}
}

0 comments on commit 3c6367b

Please sign in to comment.