markbaker/complex
PHP class library for complex number math. Create and operate on complex values with add/subtract/multiply/divide plus polar functions (theta, rho), conjugate/inverse, roots, logs, exponentials, powers, and a full set of trig and hyperbolic functions.
Install via Composer:
composer require markbaker/complex:^1.0
Begin using complex numbers by importing the core class and creating instances—strings are most intuitive for real-world use:
use Complex\Complex;
$impedance = new Complex('3+4j'); // Engineering-style suffix
$phasor = Complex::fromString('5∠30°'); // Only if manually parsed; native parser doesn’t support polar notation
First use case: Calculate total impedance in an RLC circuit:
$resistor = new Complex('10+0j');
$inductor = new Complex('0+25j');
$capacitor = new Complex('0-15j');
$total = $resistor->add($inductor)->add($capacitor);
echo $total; // Outputs: 10+10j
// app/Services/ElectricalCircuitService.php
public function calculateImpedance(): Complex
{
return collect($components)
->reduce(fn($carry, $component) => $carry->add($component->impedance), new Complex('0+0j'));
}
// In a FormRequest or controller
$z = new Complex($request->input('complex_value')); // Throws exception on invalid format
$magnitudes = array_map(
fn($bin) => Complex\Functions::abs($bin),
$fftResult
);
$amplitude = (new Complex($initialState))
->multiply($propagator)
->cos() // e.g., time evolution operator approximation
->multiply($potential);
$z->add($w) returns a new object, no mutation occurs:
// Common bug: silently ignoring return value
$z->add($w);
// ❌ $z is unchanged!
// ✅ Do this:
$z = $z->add($w);
complex_add(), switch to markbaker/complex-functions. markbaker/complex only provides the object API now.'j' (engineering convention) in constructors, output always uses 'i'. Convert with toString('j') if needed for output compatibility.pow() requires a real exponent—pass as second arg to static call or single arg to method:
Complex\Functions::pow($z, 2.5); // ✅
$z->pow(2.5); // ✅
$z->pow($complexExponent); // ❌ Throws TypeError
var_dump() shows internal structure (hard to read):
Log::info('Phase shift: ' . $phasor->toString()); // Prefer this
Complex or wrap in value objects:
final class QuantumState extends Complex
{
public function normalize(): self
{
$norm = Complex\Functions::abs($this);
return new self($this->divide($norm));
}
}
Complex objects when possible (e.g., store Complex in cache instead of strings).How can I help you explore Laravel packages today?