Additional Operations
In more advanced use cases, you might want to implement additional operations such as division, magnitude calculation, and conjugate.
Example:
PHP
<?php class ComplexNumber { private $real ; private $imaginary ; public function __construct( $real , $imaginary ) { $this ->real = $real ; $this ->imaginary = $imaginary ; } public function divide(ComplexNumber $complexNumber ) { $denominator = $complexNumber ->getReal()**2 + $complexNumber ->getImaginary()**2; $real = ( $this ->real * $complexNumber ->getReal() + $this ->imaginary * $complexNumber ->getImaginary()) / $denominator ; $imaginary = ( $this ->imaginary * $complexNumber ->getReal() - $this ->real * $complexNumber ->getImaginary()) / $denominator ; return new ComplexNumber( $real , $imaginary ); } public function magnitude() { return sqrt( $this ->real**2 + $this ->imaginary**2); } public function conjugate() { return new ComplexNumber( $this ->real, - $this ->imaginary); } public function __toString() { return "({$this->real}, {$this->imaginary}i)" ; } public function getReal() { return $this ->real; } public function getImaginary() { return $this ->imaginary; } } // Driver code $complex1 = new ComplexNumber(2, 3); $complex2 = new ComplexNumber(1, -2); $quotient = $complex1 ->divide( $complex2 ); $magnitude = $complex1 ->magnitude(); $conjugate = $complex1 ->conjugate(); echo "Quotient: $quotient, Magnitude: $magnitude, Conjugate: $conjugate" ; ?> |
Quotient: (-0.8, 1.4i), Magnitude: 3.605551275464, Conjugate: (2, -3i)
Complex Numbers in PHP
In the mathematical computations, complex numbers play a crucial role, especially in fields like engineering and physics. A complex number is a combination of a real part and an imaginary part, often expressed as a + bi, where a is the real part, b is the imaginary part, and i is the imaginary unit. In this article, we will explore PHP for handling complex numbers.