pow.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. <?php
  2. /**
  3. *
  4. * Function code for the complex pow() function
  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. * Returns a complex number raised to a power.
  12. *
  13. * @param Complex|mixed $complex Complex number or a numeric value.
  14. * @param float|integer $power The power to raise this value to
  15. * @return Complex The complex argument raised to the real power.
  16. * @throws Exception If the power argument isn't a valid real
  17. */
  18. function pow($complex, $power)
  19. {
  20. $complex = Complex::validateComplexArgument($complex);
  21. if (!is_numeric($power)) {
  22. throw new Exception('Power argument must be a real number');
  23. }
  24. if ($complex->getImaginary() == 0.0 && $complex->getReal() >= 0.0) {
  25. return new Complex(\pow($complex->getReal(), $power));
  26. }
  27. $rValue = \sqrt(($complex->getReal() * $complex->getReal()) + ($complex->getImaginary() * $complex->getImaginary()));
  28. $rPower = \pow($rValue, $power);
  29. $theta = $complex->argument() * $power;
  30. if ($theta == 0) {
  31. return new Complex(1);
  32. }
  33. return new Complex($rPower * \cos($theta), $rPower * \sin($theta), $complex->getSuffix());
  34. }