Basic Complex Number Class
Let’s start by creating a basic PHP class to represent complex numbers. This class will include methods for addition, subtraction, multiplication, and string representation of complex numbers.
Example:
PHP
<?php class ComplexNumber { private $real ; private $imaginary ; public function __construct( $real , $imaginary ) { $this ->real = $real ; $this ->imaginary = $imaginary ; } public function add(ComplexNumber $complexNumber ) { return new ComplexNumber( $this ->real + $complexNumber ->getReal(), $this ->imaginary + $complexNumber ->getImaginary() ); } public function subtract(ComplexNumber $complexNumber ) { return new ComplexNumber( $this ->real - $complexNumber ->getReal(), $this ->imaginary - $complexNumber ->getImaginary() ); } public function multiply(ComplexNumber $complexNumber ) { $real = $this ->real * $complexNumber ->getReal() - $this ->imaginary * $complexNumber ->getImaginary(); $imaginary = $this ->real * $complexNumber ->getImaginary() + $this ->imaginary * $complexNumber ->getReal(); return new ComplexNumber( $real , $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); $sum = $complex1 ->add( $complex2 ); $difference = $complex1 ->subtract( $complex2 ); $product = $complex1 ->multiply( $complex2 ); echo "Sum: $sum, Difference: $difference, Product: $product" ; ?> |
Sum: (3, 1i), Difference: (1, 5i), Product: (8, -1i)
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.