add.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /**
  3. *
  4. * Function code for the complex addition operation
  5. *
  6. * @copyright Copyright (c) 2013-2018 Mark Baker (https://github.com/MarkBaker/PHPComplex)
  7. * @license https://opensource.org/licenses/MIT MIT
  8. */
  9. namespace Complex;
  10. /**
  11. * Adds two or more complex numbers
  12. *
  13. * @param array of string|integer|float|Complex $complexValues The numbers to add
  14. * @return Complex
  15. */
  16. function add(...$complexValues)
  17. {
  18. if (count($complexValues) < 2) {
  19. throw new \Exception('This function requires at least 2 arguments');
  20. }
  21. $base = array_shift($complexValues);
  22. $result = clone Complex::validateComplexArgument($base);
  23. foreach ($complexValues as $complex) {
  24. $complex = Complex::validateComplexArgument($complex);
  25. if ($result->isComplex() && $complex->isComplex() &&
  26. $result->getSuffix() !== $complex->getSuffix()) {
  27. throw new Exception('Suffix Mismatch');
  28. }
  29. $real = $result->getReal() + $complex->getReal();
  30. $imaginary = $result->getImaginary() + $complex->getImaginary();
  31. $result = new Complex(
  32. $real,
  33. $imaginary,
  34. ($imaginary == 0.0) ? null : max($result->getSuffix(), $complex->getSuffix())
  35. );
  36. }
  37. return $result;
  38. }