phpmath / complex
A PHP library to work with immutable complex numbers.
Requires
- php: ^8.4
Requires (Dev)
- phpmath/coding-standard: ^2.0
- phpstan/phpstan: ^2.3
- phpunit/phpunit: ^13.4
Suggests
None
Provides
None
Conflicts
None
Replaces
None
This package is auto-updated.
Last update: 2026-11-24 12:59:30 UTC
README
A PHP library to work with immutable complex numbers.
Documentation
The full documentation is at https://phpmath.github.io/complex/. Every change is listed in the changelog and every release on the releases page.
Install
composer require phpmath/complex
Requirements
- PHP 8.4 or newer
Usage
Every complex number is an immutable value object with a float real and a float imaginary part. Operations never change the instance they are called on, they return a new instance.
use PHPMath\Complex\Complex; $a = Complex::of(3, 4); $b = Complex::of(1, -2); echo $a->add($b); // 4+2i echo $a->multiply($b); // 11-2i echo $a->divide($b); // -1+2i echo $a->modulus(); // 5 echo $a->conjugate(); // 3-4i echo Complex::i()->pow(2); // -1+0i echo Complex::of(-4)->sqrt(); // 0+2i $roots = Complex::one()->roots(3); // list of the three cube roots of unity $a->equals(Complex::of(3.0000000001, 4), 1e-6); // true
Features
- Creating numbers with
of(),fromPolar(),zero(),one()andi(). - Reading
real(),imaginary(),modulus()andargument(). - Arithmetic with
add(),subtract(),multiply(),divide(),negate(),conjugate()andreciprocal(). - Powers with
pow()(integer and real exponents), the principalsqrt(),exp()andlog(), and all n-throots(). - Comparing with
equals(), which accepts an absolute tolerance, and formatting with__toString()(3+4i).
Invalid input is reported with exceptions in the PHPMath\Complex\Exception namespace, all of which implement
ComplexException: InvalidValueException, DivisionByZeroException and UndefinedResultException.
Development
composer test
composer test-coverage
composer analyse
composer check-style
composer fix-style
Contributing
All contributions are welcome. Open an issue or a pull request on GitHub. Please follow the coding standard and add tests.
Security
If you discover a security issue, please create an issue in the issue tracker.
Credits
License
The MIT License (MIT). Please see License File for more information.