Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Complex Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

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

Implementation Patterns

  • Service Encapsulation: Wrap complex operations in dedicated Laravel services to isolate math logic:
    // app/Services/ElectricalCircuitService.php
    public function calculateImpedance(): Complex
    {
        return collect($components)
            ->reduce(fn($carry, $component) => $carry->add($component->impedance), new Complex('0+0j'));
    }
    
  • Input Sanitization & Validation: Leverage the parser to validate complex number inputs from requests:
    // In a FormRequest or controller
    $z = new Complex($request->input('complex_value')); // Throws exception on invalid format
    
  • Batch Processing: Use static methods for functional pipelines (e.g., processing FFT bin data):
    $magnitudes = array_map(
        fn($bin) => Complex\Functions::abs($bin),
        $fftResult
    );
    
  • Fluent Chaining for Physics Simulations: Chain calculations in wave/quantum mechanics:
    $amplitude = (new Complex($initialState))
        ->multiply($propagator)
        ->cos() // e.g., time evolution operator approximation
        ->multiply($potential);
    

Gotchas and Tips

  • Immutability Trap: Always reassign results—$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);
    
  • Version 3.x Breakage: If upgrading from pre-v3 code using procedural calls like complex_add(), switch to markbaker/complex-functions. markbaker/complex only provides the object API now.
  • Suffix Quirks: While you can use 'j' (engineering convention) in constructors, output always uses 'i'. Convert with toString('j') if needed for output compatibility.
  • Power Operation Signature: 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
    
  • Debugging & Logging: Cast to string explicitly; var_dump() shows internal structure (hard to read):
    Log::info('Phase shift: ' . $phasor->toString()); // Prefer this
    
  • Extensibility: For domain-specific behavior (e.g., quantum state normalization), extend 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));
        }
    }
    
  • Performance Tip: Avoid unnecessary parsing—reuse existing Complex objects when possible (e.g., store Complex in cache instead of strings).
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport
twbs/bootstrap4