Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1889 lines
44 KiB

  1. #
  2. # Complex numbers and associated mathematical functions
  3. # -- Raphael Manfredi Since Sep 1996
  4. # -- Jarkko Hietaniemi Since Mar 1997
  5. # -- Daniel S. Lewart Since Sep 1997
  6. #
  7. package Math::Complex;
  8. our($VERSION, @ISA, @EXPORT, %EXPORT_TAGS, $Inf);
  9. $VERSION = 1.31;
  10. BEGIN {
  11. unless ($^O eq 'unicosmk') {
  12. my $e = $!;
  13. # We do want an arithmetic overflow, Inf INF inf Infinity:.
  14. undef $Inf unless eval <<'EOE' and $Inf =~ /^inf(?:inity)?$/i;
  15. local $SIG{FPE} = sub {die};
  16. my $t = CORE::exp 30;
  17. $Inf = CORE::exp $t;
  18. EOE
  19. if (!defined $Inf) { # Try a different method
  20. undef $Inf unless eval <<'EOE' and $Inf =~ /^inf(?:inity)?$/i;
  21. local $SIG{FPE} = sub {die};
  22. my $t = 1;
  23. $Inf = $t + "1e99999999999999999999999999999999";
  24. EOE
  25. }
  26. $! = $e; # Clear ERANGE.
  27. }
  28. $Inf = "Inf" if !defined $Inf || !($Inf > 0); # Desperation.
  29. }
  30. use strict;
  31. my $i;
  32. my %LOGN;
  33. require Exporter;
  34. @ISA = qw(Exporter);
  35. my @trig = qw(
  36. pi
  37. tan
  38. csc cosec sec cot cotan
  39. asin acos atan
  40. acsc acosec asec acot acotan
  41. sinh cosh tanh
  42. csch cosech sech coth cotanh
  43. asinh acosh atanh
  44. acsch acosech asech acoth acotanh
  45. );
  46. @EXPORT = (qw(
  47. i Re Im rho theta arg
  48. sqrt log ln
  49. log10 logn cbrt root
  50. cplx cplxe
  51. ),
  52. @trig);
  53. %EXPORT_TAGS = (
  54. 'trig' => [@trig],
  55. );
  56. use overload
  57. '+' => \&plus,
  58. '-' => \&minus,
  59. '*' => \&multiply,
  60. '/' => \&divide,
  61. '**' => \&power,
  62. '==' => \&numeq,
  63. '<=>' => \&spaceship,
  64. 'neg' => \&negate,
  65. '~' => \&conjugate,
  66. 'abs' => \&abs,
  67. 'sqrt' => \&sqrt,
  68. 'exp' => \&exp,
  69. 'log' => \&log,
  70. 'sin' => \&sin,
  71. 'cos' => \&cos,
  72. 'tan' => \&tan,
  73. 'atan2' => \&atan2,
  74. qw("" stringify);
  75. #
  76. # Package "privates"
  77. #
  78. my %DISPLAY_FORMAT = ('style' => 'cartesian',
  79. 'polar_pretty_print' => 1);
  80. my $eps = 1e-14; # Epsilon
  81. #
  82. # Object attributes (internal):
  83. # cartesian [real, imaginary] -- cartesian form
  84. # polar [rho, theta] -- polar form
  85. # c_dirty cartesian form not up-to-date
  86. # p_dirty polar form not up-to-date
  87. # display display format (package's global when not set)
  88. #
  89. # Die on bad *make() arguments.
  90. sub _cannot_make {
  91. die "@{[(caller(1))[3]]}: Cannot take $_[0] of $_[1].\n";
  92. }
  93. #
  94. # ->make
  95. #
  96. # Create a new complex number (cartesian form)
  97. #
  98. sub make {
  99. my $self = bless {}, shift;
  100. my ($re, $im) = @_;
  101. my $rre = ref $re;
  102. if ( $rre ) {
  103. if ( $rre eq ref $self ) {
  104. $re = Re($re);
  105. } else {
  106. _cannot_make("real part", $rre);
  107. }
  108. }
  109. my $rim = ref $im;
  110. if ( $rim ) {
  111. if ( $rim eq ref $self ) {
  112. $im = Im($im);
  113. } else {
  114. _cannot_make("imaginary part", $rim);
  115. }
  116. }
  117. $self->{'cartesian'} = [ $re, $im ];
  118. $self->{c_dirty} = 0;
  119. $self->{p_dirty} = 1;
  120. $self->display_format('cartesian');
  121. return $self;
  122. }
  123. #
  124. # ->emake
  125. #
  126. # Create a new complex number (exponential form)
  127. #
  128. sub emake {
  129. my $self = bless {}, shift;
  130. my ($rho, $theta) = @_;
  131. my $rrh = ref $rho;
  132. if ( $rrh ) {
  133. if ( $rrh eq ref $self ) {
  134. $rho = rho($rho);
  135. } else {
  136. _cannot_make("rho", $rrh);
  137. }
  138. }
  139. my $rth = ref $theta;
  140. if ( $rth ) {
  141. if ( $rth eq ref $self ) {
  142. $theta = theta($theta);
  143. } else {
  144. _cannot_make("theta", $rth);
  145. }
  146. }
  147. if ($rho < 0) {
  148. $rho = -$rho;
  149. $theta = ($theta <= 0) ? $theta + pi() : $theta - pi();
  150. }
  151. $self->{'polar'} = [$rho, $theta];
  152. $self->{p_dirty} = 0;
  153. $self->{c_dirty} = 1;
  154. $self->display_format('polar');
  155. return $self;
  156. }
  157. sub new { &make } # For backward compatibility only.
  158. #
  159. # cplx
  160. #
  161. # Creates a complex number from a (re, im) tuple.
  162. # This avoids the burden of writing Math::Complex->make(re, im).
  163. #
  164. sub cplx {
  165. my ($re, $im) = @_;
  166. return __PACKAGE__->make($re, defined $im ? $im : 0);
  167. }
  168. #
  169. # cplxe
  170. #
  171. # Creates a complex number from a (rho, theta) tuple.
  172. # This avoids the burden of writing Math::Complex->emake(rho, theta).
  173. #
  174. sub cplxe {
  175. my ($rho, $theta) = @_;
  176. return __PACKAGE__->emake($rho, defined $theta ? $theta : 0);
  177. }
  178. #
  179. # pi
  180. #
  181. # The number defined as pi = 180 degrees
  182. #
  183. sub pi () { 4 * CORE::atan2(1, 1) }
  184. #
  185. # pit2
  186. #
  187. # The full circle
  188. #
  189. sub pit2 () { 2 * pi }
  190. #
  191. # pip2
  192. #
  193. # The quarter circle
  194. #
  195. sub pip2 () { pi / 2 }
  196. #
  197. # deg1
  198. #
  199. # One degree in radians, used in stringify_polar.
  200. #
  201. sub deg1 () { pi / 180 }
  202. #
  203. # uplog10
  204. #
  205. # Used in log10().
  206. #
  207. sub uplog10 () { 1 / CORE::log(10) }
  208. #
  209. # i
  210. #
  211. # The number defined as i*i = -1;
  212. #
  213. sub i () {
  214. return $i if ($i);
  215. $i = bless {};
  216. $i->{'cartesian'} = [0, 1];
  217. $i->{'polar'} = [1, pip2];
  218. $i->{c_dirty} = 0;
  219. $i->{p_dirty} = 0;
  220. return $i;
  221. }
  222. #
  223. # ip2
  224. #
  225. # Half of i.
  226. #
  227. sub ip2 () { i / 2 }
  228. #
  229. # Attribute access/set routines
  230. #
  231. sub cartesian {$_[0]->{c_dirty} ?
  232. $_[0]->update_cartesian : $_[0]->{'cartesian'}}
  233. sub polar {$_[0]->{p_dirty} ?
  234. $_[0]->update_polar : $_[0]->{'polar'}}
  235. sub set_cartesian { $_[0]->{p_dirty}++; $_[0]->{'cartesian'} = $_[1] }
  236. sub set_polar { $_[0]->{c_dirty}++; $_[0]->{'polar'} = $_[1] }
  237. #
  238. # ->update_cartesian
  239. #
  240. # Recompute and return the cartesian form, given accurate polar form.
  241. #
  242. sub update_cartesian {
  243. my $self = shift;
  244. my ($r, $t) = @{$self->{'polar'}};
  245. $self->{c_dirty} = 0;
  246. return $self->{'cartesian'} = [$r * CORE::cos($t), $r * CORE::sin($t)];
  247. }
  248. #
  249. #
  250. # ->update_polar
  251. #
  252. # Recompute and return the polar form, given accurate cartesian form.
  253. #
  254. sub update_polar {
  255. my $self = shift;
  256. my ($x, $y) = @{$self->{'cartesian'}};
  257. $self->{p_dirty} = 0;
  258. return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
  259. return $self->{'polar'} = [CORE::sqrt($x*$x + $y*$y),
  260. CORE::atan2($y, $x)];
  261. }
  262. #
  263. # (plus)
  264. #
  265. # Computes z1+z2.
  266. #
  267. sub plus {
  268. my ($z1, $z2, $regular) = @_;
  269. my ($re1, $im1) = @{$z1->cartesian};
  270. $z2 = cplx($z2) unless ref $z2;
  271. my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  272. unless (defined $regular) {
  273. $z1->set_cartesian([$re1 + $re2, $im1 + $im2]);
  274. return $z1;
  275. }
  276. return (ref $z1)->make($re1 + $re2, $im1 + $im2);
  277. }
  278. #
  279. # (minus)
  280. #
  281. # Computes z1-z2.
  282. #
  283. sub minus {
  284. my ($z1, $z2, $inverted) = @_;
  285. my ($re1, $im1) = @{$z1->cartesian};
  286. $z2 = cplx($z2) unless ref $z2;
  287. my ($re2, $im2) = @{$z2->cartesian};
  288. unless (defined $inverted) {
  289. $z1->set_cartesian([$re1 - $re2, $im1 - $im2]);
  290. return $z1;
  291. }
  292. return $inverted ?
  293. (ref $z1)->make($re2 - $re1, $im2 - $im1) :
  294. (ref $z1)->make($re1 - $re2, $im1 - $im2);
  295. }
  296. #
  297. # (multiply)
  298. #
  299. # Computes z1*z2.
  300. #
  301. sub multiply {
  302. my ($z1, $z2, $regular) = @_;
  303. if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
  304. # if both polar better use polar to avoid rounding errors
  305. my ($r1, $t1) = @{$z1->polar};
  306. my ($r2, $t2) = @{$z2->polar};
  307. my $t = $t1 + $t2;
  308. if ($t > pi()) { $t -= pit2 }
  309. elsif ($t <= -pi()) { $t += pit2 }
  310. unless (defined $regular) {
  311. $z1->set_polar([$r1 * $r2, $t]);
  312. return $z1;
  313. }
  314. return (ref $z1)->emake($r1 * $r2, $t);
  315. } else {
  316. my ($x1, $y1) = @{$z1->cartesian};
  317. if (ref $z2) {
  318. my ($x2, $y2) = @{$z2->cartesian};
  319. return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2);
  320. } else {
  321. return (ref $z1)->make($x1*$z2, $y1*$z2);
  322. }
  323. }
  324. }
  325. #
  326. # _divbyzero
  327. #
  328. # Die on division by zero.
  329. #
  330. sub _divbyzero {
  331. my $mess = "$_[0]: Division by zero.\n";
  332. if (defined $_[1]) {
  333. $mess .= "(Because in the definition of $_[0], the divisor ";
  334. $mess .= "$_[1] " unless ("$_[1]" eq '0');
  335. $mess .= "is 0)\n";
  336. }
  337. my @up = caller(1);
  338. $mess .= "Died at $up[1] line $up[2].\n";
  339. die $mess;
  340. }
  341. #
  342. # (divide)
  343. #
  344. # Computes z1/z2.
  345. #
  346. sub divide {
  347. my ($z1, $z2, $inverted) = @_;
  348. if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
  349. # if both polar better use polar to avoid rounding errors
  350. my ($r1, $t1) = @{$z1->polar};
  351. my ($r2, $t2) = @{$z2->polar};
  352. my $t;
  353. if ($inverted) {
  354. _divbyzero "$z2/0" if ($r1 == 0);
  355. $t = $t2 - $t1;
  356. if ($t > pi()) { $t -= pit2 }
  357. elsif ($t <= -pi()) { $t += pit2 }
  358. return (ref $z1)->emake($r2 / $r1, $t);
  359. } else {
  360. _divbyzero "$z1/0" if ($r2 == 0);
  361. $t = $t1 - $t2;
  362. if ($t > pi()) { $t -= pit2 }
  363. elsif ($t <= -pi()) { $t += pit2 }
  364. return (ref $z1)->emake($r1 / $r2, $t);
  365. }
  366. } else {
  367. my ($d, $x2, $y2);
  368. if ($inverted) {
  369. ($x2, $y2) = @{$z1->cartesian};
  370. $d = $x2*$x2 + $y2*$y2;
  371. _divbyzero "$z2/0" if $d == 0;
  372. return (ref $z1)->make(($x2*$z2)/$d, -($y2*$z2)/$d);
  373. } else {
  374. my ($x1, $y1) = @{$z1->cartesian};
  375. if (ref $z2) {
  376. ($x2, $y2) = @{$z2->cartesian};
  377. $d = $x2*$x2 + $y2*$y2;
  378. _divbyzero "$z1/0" if $d == 0;
  379. my $u = ($x1*$x2 + $y1*$y2)/$d;
  380. my $v = ($y1*$x2 - $x1*$y2)/$d;
  381. return (ref $z1)->make($u, $v);
  382. } else {
  383. _divbyzero "$z1/0" if $z2 == 0;
  384. return (ref $z1)->make($x1/$z2, $y1/$z2);
  385. }
  386. }
  387. }
  388. }
  389. #
  390. # (power)
  391. #
  392. # Computes z1**z2 = exp(z2 * log z1)).
  393. #
  394. sub power {
  395. my ($z1, $z2, $inverted) = @_;
  396. if ($inverted) {
  397. return 1 if $z1 == 0 || $z2 == 1;
  398. return 0 if $z2 == 0 && Re($z1) > 0;
  399. } else {
  400. return 1 if $z2 == 0 || $z1 == 1;
  401. return 0 if $z1 == 0 && Re($z2) > 0;
  402. }
  403. my $w = $inverted ? &exp($z1 * &log($z2))
  404. : &exp($z2 * &log($z1));
  405. # If both arguments cartesian, return cartesian, else polar.
  406. return $z1->{c_dirty} == 0 &&
  407. (not ref $z2 or $z2->{c_dirty} == 0) ?
  408. cplx(@{$w->cartesian}) : $w;
  409. }
  410. #
  411. # (spaceship)
  412. #
  413. # Computes z1 <=> z2.
  414. # Sorts on the real part first, then on the imaginary part. Thus 2-4i < 3+8i.
  415. #
  416. sub spaceship {
  417. my ($z1, $z2, $inverted) = @_;
  418. my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
  419. my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  420. my $sgn = $inverted ? -1 : 1;
  421. return $sgn * ($re1 <=> $re2) if $re1 != $re2;
  422. return $sgn * ($im1 <=> $im2);
  423. }
  424. #
  425. # (numeq)
  426. #
  427. # Computes z1 == z2.
  428. #
  429. # (Required in addition to spaceship() because of NaNs.)
  430. sub numeq {
  431. my ($z1, $z2, $inverted) = @_;
  432. my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
  433. my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  434. return $re1 == $re2 && $im1 == $im2 ? 1 : 0;
  435. }
  436. #
  437. # (negate)
  438. #
  439. # Computes -z.
  440. #
  441. sub negate {
  442. my ($z) = @_;
  443. if ($z->{c_dirty}) {
  444. my ($r, $t) = @{$z->polar};
  445. $t = ($t <= 0) ? $t + pi : $t - pi;
  446. return (ref $z)->emake($r, $t);
  447. }
  448. my ($re, $im) = @{$z->cartesian};
  449. return (ref $z)->make(-$re, -$im);
  450. }
  451. #
  452. # (conjugate)
  453. #
  454. # Compute complex's conjugate.
  455. #
  456. sub conjugate {
  457. my ($z) = @_;
  458. if ($z->{c_dirty}) {
  459. my ($r, $t) = @{$z->polar};
  460. return (ref $z)->emake($r, -$t);
  461. }
  462. my ($re, $im) = @{$z->cartesian};
  463. return (ref $z)->make($re, -$im);
  464. }
  465. #
  466. # (abs)
  467. #
  468. # Compute or set complex's norm (rho).
  469. #
  470. sub abs {
  471. my ($z, $rho) = @_;
  472. unless (ref $z) {
  473. if (@_ == 2) {
  474. $_[0] = $_[1];
  475. } else {
  476. return CORE::abs($z);
  477. }
  478. }
  479. if (defined $rho) {
  480. $z->{'polar'} = [ $rho, ${$z->polar}[1] ];
  481. $z->{p_dirty} = 0;
  482. $z->{c_dirty} = 1;
  483. return $rho;
  484. } else {
  485. return ${$z->polar}[0];
  486. }
  487. }
  488. sub _theta {
  489. my $theta = $_[0];
  490. if ($$theta > pi()) { $$theta -= pit2 }
  491. elsif ($$theta <= -pi()) { $$theta += pit2 }
  492. }
  493. #
  494. # arg
  495. #
  496. # Compute or set complex's argument (theta).
  497. #
  498. sub arg {
  499. my ($z, $theta) = @_;
  500. return $z unless ref $z;
  501. if (defined $theta) {
  502. _theta(\$theta);
  503. $z->{'polar'} = [ ${$z->polar}[0], $theta ];
  504. $z->{p_dirty} = 0;
  505. $z->{c_dirty} = 1;
  506. } else {
  507. $theta = ${$z->polar}[1];
  508. _theta(\$theta);
  509. }
  510. return $theta;
  511. }
  512. #
  513. # (sqrt)
  514. #
  515. # Compute sqrt(z).
  516. #
  517. # It is quite tempting to use wantarray here so that in list context
  518. # sqrt() would return the two solutions. This, however, would
  519. # break things like
  520. #
  521. # print "sqrt(z) = ", sqrt($z), "\n";
  522. #
  523. # The two values would be printed side by side without no intervening
  524. # whitespace, quite confusing.
  525. # Therefore if you want the two solutions use the root().
  526. #
  527. sub sqrt {
  528. my ($z) = @_;
  529. my ($re, $im) = ref $z ? @{$z->cartesian} : ($z, 0);
  530. return $re < 0 ? cplx(0, CORE::sqrt(-$re)) : CORE::sqrt($re)
  531. if $im == 0;
  532. my ($r, $t) = @{$z->polar};
  533. return (ref $z)->emake(CORE::sqrt($r), $t/2);
  534. }
  535. #
  536. # cbrt
  537. #
  538. # Compute cbrt(z) (cubic root).
  539. #
  540. # Why are we not returning three values? The same answer as for sqrt().
  541. #
  542. sub cbrt {
  543. my ($z) = @_;
  544. return $z < 0 ?
  545. -CORE::exp(CORE::log(-$z)/3) :
  546. ($z > 0 ? CORE::exp(CORE::log($z)/3): 0)
  547. unless ref $z;
  548. my ($r, $t) = @{$z->polar};
  549. return 0 if $r == 0;
  550. return (ref $z)->emake(CORE::exp(CORE::log($r)/3), $t/3);
  551. }
  552. #
  553. # _rootbad
  554. #
  555. # Die on bad root.
  556. #
  557. sub _rootbad {
  558. my $mess = "Root $_[0] illegal, root rank must be positive integer.\n";
  559. my @up = caller(1);
  560. $mess .= "Died at $up[1] line $up[2].\n";
  561. die $mess;
  562. }
  563. #
  564. # root
  565. #
  566. # Computes all nth root for z, returning an array whose size is n.
  567. # `n' must be a positive integer.
  568. #
  569. # The roots are given by (for k = 0..n-1):
  570. #
  571. # z^(1/n) = r^(1/n) (cos ((t+2 k pi)/n) + i sin ((t+2 k pi)/n))
  572. #
  573. sub root {
  574. my ($z, $n) = @_;
  575. _rootbad($n) if ($n < 1 or int($n) != $n);
  576. my ($r, $t) = ref $z ?
  577. @{$z->polar} : (CORE::abs($z), $z >= 0 ? 0 : pi);
  578. my @root;
  579. my $k;
  580. my $theta_inc = pit2 / $n;
  581. my $rho = $r ** (1/$n);
  582. my $theta;
  583. my $cartesian = ref $z && $z->{c_dirty} == 0;
  584. for ($k = 0, $theta = $t / $n; $k < $n; $k++, $theta += $theta_inc) {
  585. my $w = cplxe($rho, $theta);
  586. # Yes, $cartesian is loop invariant.
  587. push @root, $cartesian ? cplx(@{$w->cartesian}) : $w;
  588. }
  589. return @root;
  590. }
  591. #
  592. # Re
  593. #
  594. # Return or set Re(z).
  595. #
  596. sub Re {
  597. my ($z, $Re) = @_;
  598. return $z unless ref $z;
  599. if (defined $Re) {
  600. $z->{'cartesian'} = [ $Re, ${$z->cartesian}[1] ];
  601. $z->{c_dirty} = 0;
  602. $z->{p_dirty} = 1;
  603. } else {
  604. return ${$z->cartesian}[0];
  605. }
  606. }
  607. #
  608. # Im
  609. #
  610. # Return or set Im(z).
  611. #
  612. sub Im {
  613. my ($z, $Im) = @_;
  614. return 0 unless ref $z;
  615. if (defined $Im) {
  616. $z->{'cartesian'} = [ ${$z->cartesian}[0], $Im ];
  617. $z->{c_dirty} = 0;
  618. $z->{p_dirty} = 1;
  619. } else {
  620. return ${$z->cartesian}[1];
  621. }
  622. }
  623. #
  624. # rho
  625. #
  626. # Return or set rho(w).
  627. #
  628. sub rho {
  629. Math::Complex::abs(@_);
  630. }
  631. #
  632. # theta
  633. #
  634. # Return or set theta(w).
  635. #
  636. sub theta {
  637. Math::Complex::arg(@_);
  638. }
  639. #
  640. # (exp)
  641. #
  642. # Computes exp(z).
  643. #
  644. sub exp {
  645. my ($z) = @_;
  646. my ($x, $y) = @{$z->cartesian};
  647. return (ref $z)->emake(CORE::exp($x), $y);
  648. }
  649. #
  650. # _logofzero
  651. #
  652. # Die on logarithm of zero.
  653. #
  654. sub _logofzero {
  655. my $mess = "$_[0]: Logarithm of zero.\n";
  656. if (defined $_[1]) {
  657. $mess .= "(Because in the definition of $_[0], the argument ";
  658. $mess .= "$_[1] " unless ($_[1] eq '0');
  659. $mess .= "is 0)\n";
  660. }
  661. my @up = caller(1);
  662. $mess .= "Died at $up[1] line $up[2].\n";
  663. die $mess;
  664. }
  665. #
  666. # (log)
  667. #
  668. # Compute log(z).
  669. #
  670. sub log {
  671. my ($z) = @_;
  672. unless (ref $z) {
  673. _logofzero("log") if $z == 0;
  674. return $z > 0 ? CORE::log($z) : cplx(CORE::log(-$z), pi);
  675. }
  676. my ($r, $t) = @{$z->polar};
  677. _logofzero("log") if $r == 0;
  678. if ($t > pi()) { $t -= pit2 }
  679. elsif ($t <= -pi()) { $t += pit2 }
  680. return (ref $z)->make(CORE::log($r), $t);
  681. }
  682. #
  683. # ln
  684. #
  685. # Alias for log().
  686. #
  687. sub ln { Math::Complex::log(@_) }
  688. #
  689. # log10
  690. #
  691. # Compute log10(z).
  692. #
  693. sub log10 {
  694. return Math::Complex::log($_[0]) * uplog10;
  695. }
  696. #
  697. # logn
  698. #
  699. # Compute logn(z,n) = log(z) / log(n)
  700. #
  701. sub logn {
  702. my ($z, $n) = @_;
  703. $z = cplx($z, 0) unless ref $z;
  704. my $logn = $LOGN{$n};
  705. $logn = $LOGN{$n} = CORE::log($n) unless defined $logn; # Cache log(n)
  706. return &log($z) / $logn;
  707. }
  708. #
  709. # (cos)
  710. #
  711. # Compute cos(z) = (exp(iz) + exp(-iz))/2.
  712. #
  713. sub cos {
  714. my ($z) = @_;
  715. return CORE::cos($z) unless ref $z;
  716. my ($x, $y) = @{$z->cartesian};
  717. my $ey = CORE::exp($y);
  718. my $sx = CORE::sin($x);
  719. my $cx = CORE::cos($x);
  720. my $ey_1 = $ey ? 1 / $ey : $Inf;
  721. return (ref $z)->make($cx * ($ey + $ey_1)/2,
  722. $sx * ($ey_1 - $ey)/2);
  723. }
  724. #
  725. # (sin)
  726. #
  727. # Compute sin(z) = (exp(iz) - exp(-iz))/2.
  728. #
  729. sub sin {
  730. my ($z) = @_;
  731. return CORE::sin($z) unless ref $z;
  732. my ($x, $y) = @{$z->cartesian};
  733. my $ey = CORE::exp($y);
  734. my $sx = CORE::sin($x);
  735. my $cx = CORE::cos($x);
  736. my $ey_1 = $ey ? 1 / $ey : $Inf;
  737. return (ref $z)->make($sx * ($ey + $ey_1)/2,
  738. $cx * ($ey - $ey_1)/2);
  739. }
  740. #
  741. # tan
  742. #
  743. # Compute tan(z) = sin(z) / cos(z).
  744. #
  745. sub tan {
  746. my ($z) = @_;
  747. my $cz = &cos($z);
  748. _divbyzero "tan($z)", "cos($z)" if $cz == 0;
  749. return &sin($z) / $cz;
  750. }
  751. #
  752. # sec
  753. #
  754. # Computes the secant sec(z) = 1 / cos(z).
  755. #
  756. sub sec {
  757. my ($z) = @_;
  758. my $cz = &cos($z);
  759. _divbyzero "sec($z)", "cos($z)" if ($cz == 0);
  760. return 1 / $cz;
  761. }
  762. #
  763. # csc
  764. #
  765. # Computes the cosecant csc(z) = 1 / sin(z).
  766. #
  767. sub csc {
  768. my ($z) = @_;
  769. my $sz = &sin($z);
  770. _divbyzero "csc($z)", "sin($z)" if ($sz == 0);
  771. return 1 / $sz;
  772. }
  773. #
  774. # cosec
  775. #
  776. # Alias for csc().
  777. #
  778. sub cosec { Math::Complex::csc(@_) }
  779. #
  780. # cot
  781. #
  782. # Computes cot(z) = cos(z) / sin(z).
  783. #
  784. sub cot {
  785. my ($z) = @_;
  786. my $sz = &sin($z);
  787. _divbyzero "cot($z)", "sin($z)" if ($sz == 0);
  788. return &cos($z) / $sz;
  789. }
  790. #
  791. # cotan
  792. #
  793. # Alias for cot().
  794. #
  795. sub cotan { Math::Complex::cot(@_) }
  796. #
  797. # acos
  798. #
  799. # Computes the arc cosine acos(z) = -i log(z + sqrt(z*z-1)).
  800. #
  801. sub acos {
  802. my $z = $_[0];
  803. return CORE::atan2(CORE::sqrt(1-$z*$z), $z)
  804. if (! ref $z) && CORE::abs($z) <= 1;
  805. $z = cplx($z, 0) unless ref $z;
  806. my ($x, $y) = @{$z->cartesian};
  807. return 0 if $x == 1 && $y == 0;
  808. my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y);
  809. my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y);
  810. my $alpha = ($t1 + $t2)/2;
  811. my $beta = ($t1 - $t2)/2;
  812. $alpha = 1 if $alpha < 1;
  813. if ($beta > 1) { $beta = 1 }
  814. elsif ($beta < -1) { $beta = -1 }
  815. my $u = CORE::atan2(CORE::sqrt(1-$beta*$beta), $beta);
  816. my $v = CORE::log($alpha + CORE::sqrt($alpha*$alpha-1));
  817. $v = -$v if $y > 0 || ($y == 0 && $x < -1);
  818. return (ref $z)->make($u, $v);
  819. }
  820. #
  821. # asin
  822. #
  823. # Computes the arc sine asin(z) = -i log(iz + sqrt(1-z*z)).
  824. #
  825. sub asin {
  826. my $z = $_[0];
  827. return CORE::atan2($z, CORE::sqrt(1-$z*$z))
  828. if (! ref $z) && CORE::abs($z) <= 1;
  829. $z = cplx($z, 0) unless ref $z;
  830. my ($x, $y) = @{$z->cartesian};
  831. return 0 if $x == 0 && $y == 0;
  832. my $t1 = CORE::sqrt(($x+1)*($x+1) + $y*$y);
  833. my $t2 = CORE::sqrt(($x-1)*($x-1) + $y*$y);
  834. my $alpha = ($t1 + $t2)/2;
  835. my $beta = ($t1 - $t2)/2;
  836. $alpha = 1 if $alpha < 1;
  837. if ($beta > 1) { $beta = 1 }
  838. elsif ($beta < -1) { $beta = -1 }
  839. my $u = CORE::atan2($beta, CORE::sqrt(1-$beta*$beta));
  840. my $v = -CORE::log($alpha + CORE::sqrt($alpha*$alpha-1));
  841. $v = -$v if $y > 0 || ($y == 0 && $x < -1);
  842. return (ref $z)->make($u, $v);
  843. }
  844. #
  845. # atan
  846. #
  847. # Computes the arc tangent atan(z) = i/2 log((i+z) / (i-z)).
  848. #
  849. sub atan {
  850. my ($z) = @_;
  851. return CORE::atan2($z, 1) unless ref $z;
  852. my ($x, $y) = ref $z ? @{$z->cartesian} : ($z, 0);
  853. return 0 if $x == 0 && $y == 0;
  854. _divbyzero "atan(i)" if ( $z == i);
  855. _logofzero "atan(-i)" if (-$z == i); # -i is a bad file test...
  856. my $log = &log((i + $z) / (i - $z));
  857. return ip2 * $log;
  858. }
  859. #
  860. # asec
  861. #
  862. # Computes the arc secant asec(z) = acos(1 / z).
  863. #
  864. sub asec {
  865. my ($z) = @_;
  866. _divbyzero "asec($z)", $z if ($z == 0);
  867. return acos(1 / $z);
  868. }
  869. #
  870. # acsc
  871. #
  872. # Computes the arc cosecant acsc(z) = asin(1 / z).
  873. #
  874. sub acsc {
  875. my ($z) = @_;
  876. _divbyzero "acsc($z)", $z if ($z == 0);
  877. return asin(1 / $z);
  878. }
  879. #
  880. # acosec
  881. #
  882. # Alias for acsc().
  883. #
  884. sub acosec { Math::Complex::acsc(@_) }
  885. #
  886. # acot
  887. #
  888. # Computes the arc cotangent acot(z) = atan(1 / z)
  889. #
  890. sub acot {
  891. my ($z) = @_;
  892. _divbyzero "acot(0)" if $z == 0;
  893. return ($z >= 0) ? CORE::atan2(1, $z) : CORE::atan2(-1, -$z)
  894. unless ref $z;
  895. _divbyzero "acot(i)" if ($z - i == 0);
  896. _logofzero "acot(-i)" if ($z + i == 0);
  897. return atan(1 / $z);
  898. }
  899. #
  900. # acotan
  901. #
  902. # Alias for acot().
  903. #
  904. sub acotan { Math::Complex::acot(@_) }
  905. #
  906. # cosh
  907. #
  908. # Computes the hyperbolic cosine cosh(z) = (exp(z) + exp(-z))/2.
  909. #
  910. sub cosh {
  911. my ($z) = @_;
  912. my $ex;
  913. unless (ref $z) {
  914. $ex = CORE::exp($z);
  915. return $ex ? ($ex + 1/$ex)/2 : $Inf;
  916. }
  917. my ($x, $y) = @{$z->cartesian};
  918. $ex = CORE::exp($x);
  919. my $ex_1 = $ex ? 1 / $ex : $Inf;
  920. return (ref $z)->make(CORE::cos($y) * ($ex + $ex_1)/2,
  921. CORE::sin($y) * ($ex - $ex_1)/2);
  922. }
  923. #
  924. # sinh
  925. #
  926. # Computes the hyperbolic sine sinh(z) = (exp(z) - exp(-z))/2.
  927. #
  928. sub sinh {
  929. my ($z) = @_;
  930. my $ex;
  931. unless (ref $z) {
  932. return 0 if $z == 0;
  933. $ex = CORE::exp($z);
  934. return $ex ? ($ex - 1/$ex)/2 : "-$Inf";
  935. }
  936. my ($x, $y) = @{$z->cartesian};
  937. my $cy = CORE::cos($y);
  938. my $sy = CORE::sin($y);
  939. $ex = CORE::exp($x);
  940. my $ex_1 = $ex ? 1 / $ex : $Inf;
  941. return (ref $z)->make(CORE::cos($y) * ($ex - $ex_1)/2,
  942. CORE::sin($y) * ($ex + $ex_1)/2);
  943. }
  944. #
  945. # tanh
  946. #
  947. # Computes the hyperbolic tangent tanh(z) = sinh(z) / cosh(z).
  948. #
  949. sub tanh {
  950. my ($z) = @_;
  951. my $cz = cosh($z);
  952. _divbyzero "tanh($z)", "cosh($z)" if ($cz == 0);
  953. return sinh($z) / $cz;
  954. }
  955. #
  956. # sech
  957. #
  958. # Computes the hyperbolic secant sech(z) = 1 / cosh(z).
  959. #
  960. sub sech {
  961. my ($z) = @_;
  962. my $cz = cosh($z);
  963. _divbyzero "sech($z)", "cosh($z)" if ($cz == 0);
  964. return 1 / $cz;
  965. }
  966. #
  967. # csch
  968. #
  969. # Computes the hyperbolic cosecant csch(z) = 1 / sinh(z).
  970. #
  971. sub csch {
  972. my ($z) = @_;
  973. my $sz = sinh($z);
  974. _divbyzero "csch($z)", "sinh($z)" if ($sz == 0);
  975. return 1 / $sz;
  976. }
  977. #
  978. # cosech
  979. #
  980. # Alias for csch().
  981. #
  982. sub cosech { Math::Complex::csch(@_) }
  983. #
  984. # coth
  985. #
  986. # Computes the hyperbolic cotangent coth(z) = cosh(z) / sinh(z).
  987. #
  988. sub coth {
  989. my ($z) = @_;
  990. my $sz = sinh($z);
  991. _divbyzero "coth($z)", "sinh($z)" if $sz == 0;
  992. return cosh($z) / $sz;
  993. }
  994. #
  995. # cotanh
  996. #
  997. # Alias for coth().
  998. #
  999. sub cotanh { Math::Complex::coth(@_) }
  1000. #
  1001. # acosh
  1002. #
  1003. # Computes the arc hyperbolic cosine acosh(z) = log(z + sqrt(z*z-1)).
  1004. #
  1005. sub acosh {
  1006. my ($z) = @_;
  1007. unless (ref $z) {
  1008. $z = cplx($z, 0);
  1009. }
  1010. my ($re, $im) = @{$z->cartesian};
  1011. if ($im == 0) {
  1012. return CORE::log($re + CORE::sqrt($re*$re - 1))
  1013. if $re >= 1;
  1014. return cplx(0, CORE::atan2(CORE::sqrt(1 - $re*$re), $re))
  1015. if CORE::abs($re) < 1;
  1016. }
  1017. my $t = &sqrt($z * $z - 1) + $z;
  1018. # Try Taylor if looking bad (this usually means that
  1019. # $z was large negative, therefore the sqrt is really
  1020. # close to abs(z), summing that with z...)
  1021. $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7)
  1022. if $t == 0;
  1023. my $u = &log($t);
  1024. $u->Im(-$u->Im) if $re < 0 && $im == 0;
  1025. return $re < 0 ? -$u : $u;
  1026. }
  1027. #
  1028. # asinh
  1029. #
  1030. # Computes the arc hyperbolic sine asinh(z) = log(z + sqrt(z*z+1))
  1031. #
  1032. sub asinh {
  1033. my ($z) = @_;
  1034. unless (ref $z) {
  1035. my $t = $z + CORE::sqrt($z*$z + 1);
  1036. return CORE::log($t) if $t;
  1037. }
  1038. my $t = &sqrt($z * $z + 1) + $z;
  1039. # Try Taylor if looking bad (this usually means that
  1040. # $z was large negative, therefore the sqrt is really
  1041. # close to abs(z), summing that with z...)
  1042. $t = 1/(2 * $z) - 1/(8 * $z**3) + 1/(16 * $z**5) - 5/(128 * $z**7)
  1043. if $t == 0;
  1044. return &log($t);
  1045. }
  1046. #
  1047. # atanh
  1048. #
  1049. # Computes the arc hyperbolic tangent atanh(z) = 1/2 log((1+z) / (1-z)).
  1050. #
  1051. sub atanh {
  1052. my ($z) = @_;
  1053. unless (ref $z) {
  1054. return CORE::log((1 + $z)/(1 - $z))/2 if CORE::abs($z) < 1;
  1055. $z = cplx($z, 0);
  1056. }
  1057. _divbyzero 'atanh(1)', "1 - $z" if (1 - $z == 0);
  1058. _logofzero 'atanh(-1)' if (1 + $z == 0);
  1059. return 0.5 * &log((1 + $z) / (1 - $z));
  1060. }
  1061. #
  1062. # asech
  1063. #
  1064. # Computes the hyperbolic arc secant asech(z) = acosh(1 / z).
  1065. #
  1066. sub asech {
  1067. my ($z) = @_;
  1068. _divbyzero 'asech(0)', "$z" if ($z == 0);
  1069. return acosh(1 / $z);
  1070. }
  1071. #
  1072. # acsch
  1073. #
  1074. # Computes the hyperbolic arc cosecant acsch(z) = asinh(1 / z).
  1075. #
  1076. sub acsch {
  1077. my ($z) = @_;
  1078. _divbyzero 'acsch(0)', $z if ($z == 0);
  1079. return asinh(1 / $z);
  1080. }
  1081. #
  1082. # acosech
  1083. #
  1084. # Alias for acosh().
  1085. #
  1086. sub acosech { Math::Complex::acsch(@_) }
  1087. #
  1088. # acoth
  1089. #
  1090. # Computes the arc hyperbolic cotangent acoth(z) = 1/2 log((1+z) / (z-1)).
  1091. #
  1092. sub acoth {
  1093. my ($z) = @_;
  1094. _divbyzero 'acoth(0)' if ($z == 0);
  1095. unless (ref $z) {
  1096. return CORE::log(($z + 1)/($z - 1))/2 if CORE::abs($z) > 1;
  1097. $z = cplx($z, 0);
  1098. }
  1099. _divbyzero 'acoth(1)', "$z - 1" if ($z - 1 == 0);
  1100. _logofzero 'acoth(-1)', "1 + $z" if (1 + $z == 0);
  1101. return &log((1 + $z) / ($z - 1)) / 2;
  1102. }
  1103. #
  1104. # acotanh
  1105. #
  1106. # Alias for acot().
  1107. #
  1108. sub acotanh { Math::Complex::acoth(@_) }
  1109. #
  1110. # (atan2)
  1111. #
  1112. # Compute atan(z1/z2).
  1113. #
  1114. sub atan2 {
  1115. my ($z1, $z2, $inverted) = @_;
  1116. my ($re1, $im1, $re2, $im2);
  1117. if ($inverted) {
  1118. ($re1, $im1) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  1119. ($re2, $im2) = @{$z1->cartesian};
  1120. } else {
  1121. ($re1, $im1) = @{$z1->cartesian};
  1122. ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
  1123. }
  1124. if ($im2 == 0) {
  1125. return CORE::atan2($re1, $re2) if $im1 == 0;
  1126. return ($im1<=>0) * pip2 if $re2 == 0;
  1127. }
  1128. my $w = atan($z1/$z2);
  1129. my ($u, $v) = ref $w ? @{$w->cartesian} : ($w, 0);
  1130. $u += pi if $re2 < 0;
  1131. $u -= pit2 if $u > pi;
  1132. return cplx($u, $v);
  1133. }
  1134. #
  1135. # display_format
  1136. # ->display_format
  1137. #
  1138. # Set (get if no argument) the display format for all complex numbers that
  1139. # don't happen to have overridden it via ->display_format
  1140. #
  1141. # When called as an object method, this actually sets the display format for
  1142. # the current object.
  1143. #
  1144. # Valid object formats are 'c' and 'p' for cartesian and polar. The first
  1145. # letter is used actually, so the type can be fully spelled out for clarity.
  1146. #
  1147. sub display_format {
  1148. my $self = shift;
  1149. my %display_format = %DISPLAY_FORMAT;
  1150. if (ref $self) { # Called as an object method
  1151. if (exists $self->{display_format}) {
  1152. my %obj = %{$self->{display_format}};
  1153. @display_format{keys %obj} = values %obj;
  1154. }
  1155. }
  1156. if (@_ == 1) {
  1157. $display_format{style} = shift;
  1158. } else {
  1159. my %new = @_;
  1160. @display_format{keys %new} = values %new;
  1161. }
  1162. if (ref $self) { # Called as an object method
  1163. $self->{display_format} = { %display_format };
  1164. return
  1165. wantarray ?
  1166. %{$self->{display_format}} :
  1167. $self->{display_format}->{style};
  1168. }
  1169. # Called as a class method
  1170. %DISPLAY_FORMAT = %display_format;
  1171. return
  1172. wantarray ?
  1173. %DISPLAY_FORMAT :
  1174. $DISPLAY_FORMAT{style};
  1175. }
  1176. #
  1177. # (stringify)
  1178. #
  1179. # Show nicely formatted complex number under its cartesian or polar form,
  1180. # depending on the current display format:
  1181. #
  1182. # . If a specific display format has been recorded for this object, use it.
  1183. # . Otherwise, use the generic current default for all complex numbers,
  1184. # which is a package global variable.
  1185. #
  1186. sub stringify {
  1187. my ($z) = shift;
  1188. my $style = $z->display_format;
  1189. $style = $DISPLAY_FORMAT{style} unless defined $style;
  1190. return $z->stringify_polar if $style =~ /^p/i;
  1191. return $z->stringify_cartesian;
  1192. }
  1193. #
  1194. # ->stringify_cartesian
  1195. #
  1196. # Stringify as a cartesian representation 'a+bi'.
  1197. #
  1198. sub stringify_cartesian {
  1199. my $z = shift;
  1200. my ($x, $y) = @{$z->cartesian};
  1201. my ($re, $im);
  1202. my %format = $z->display_format;
  1203. my $format = $format{format};
  1204. if ($x) {
  1205. if ($x =~ /^NaN[QS]?$/i) {
  1206. $re = $x;
  1207. } else {
  1208. if ($x =~ /^-?$Inf$/oi) {
  1209. $re = $x;
  1210. } else {
  1211. $re = defined $format ? sprintf($format, $x) : $x;
  1212. }
  1213. }
  1214. } else {
  1215. undef $re;
  1216. }
  1217. if ($y) {
  1218. if ($y =~ /^(NaN[QS]?)$/i) {
  1219. $im = $y;
  1220. } else {
  1221. if ($y =~ /^-?$Inf$/oi) {
  1222. $im = $y;
  1223. } else {
  1224. $im =
  1225. defined $format ?
  1226. sprintf($format, $y) :
  1227. ($y == 1 ? "" : ($y == -1 ? "-" : $y));
  1228. }
  1229. }
  1230. $im .= "i";
  1231. } else {
  1232. undef $im;
  1233. }
  1234. my $str = $re;
  1235. if (defined $im) {
  1236. if ($y < 0) {
  1237. $str .= $im;
  1238. } elsif ($y > 0 || $im =~ /^NaN[QS]?i$/i) {
  1239. $str .= "+" if defined $re;
  1240. $str .= $im;
  1241. }
  1242. } elsif (!defined $re) {
  1243. $str = "0";
  1244. }
  1245. return $str;
  1246. }
  1247. #
  1248. # ->stringify_polar
  1249. #
  1250. # Stringify as a polar representation '[r,t]'.
  1251. #
  1252. sub stringify_polar {
  1253. my $z = shift;
  1254. my ($r, $t) = @{$z->polar};
  1255. my $theta;
  1256. my %format = $z->display_format;
  1257. my $format = $format{format};
  1258. if ($t =~ /^NaN[QS]?$/i || $t =~ /^-?$Inf$/oi) {
  1259. $theta = $t;
  1260. } elsif ($t == pi) {
  1261. $theta = "pi";
  1262. } elsif ($r == 0 || $t == 0) {
  1263. $theta = defined $format ? sprintf($format, $t) : $t;
  1264. }
  1265. return "[$r,$theta]" if defined $theta;
  1266. #
  1267. # Try to identify pi/n and friends.
  1268. #
  1269. $t -= int(CORE::abs($t) / pit2) * pit2;
  1270. if ($format{polar_pretty_print} && $t) {
  1271. my ($a, $b);
  1272. for $a (2..9) {
  1273. $b = $t * $a / pi;
  1274. if ($b =~ /^-?\d+$/) {
  1275. $b = $b < 0 ? "-" : "" if CORE::abs($b) == 1;
  1276. $theta = "${b}pi/$a";
  1277. last;
  1278. }
  1279. }
  1280. }
  1281. if (defined $format) {
  1282. $r = sprintf($format, $r);
  1283. $theta = sprintf($format, $theta) unless defined $theta;
  1284. } else {
  1285. $theta = $t unless defined $theta;
  1286. }
  1287. return "[$r,$theta]";
  1288. }
  1289. 1;
  1290. __END__
  1291. =pod
  1292. =head1 NAME
  1293. Math::Complex - complex numbers and associated mathematical functions
  1294. =head1 SYNOPSIS
  1295. use Math::Complex;
  1296. $z = Math::Complex->make(5, 6);
  1297. $t = 4 - 3*i + $z;
  1298. $j = cplxe(1, 2*pi/3);
  1299. =head1 DESCRIPTION
  1300. This package lets you create and manipulate complex numbers. By default,
  1301. I<Perl> limits itself to real numbers, but an extra C<use> statement brings
  1302. full complex support, along with a full set of mathematical functions
  1303. typically associated with and/or extended to complex numbers.
  1304. If you wonder what complex numbers are, they were invented to be able to solve
  1305. the following equation:
  1306. x*x = -1
  1307. and by definition, the solution is noted I<i> (engineers use I<j> instead since
  1308. I<i> usually denotes an intensity, but the name does not matter). The number
  1309. I<i> is a pure I<imaginary> number.
  1310. The arithmetics with pure imaginary numbers works just like you would expect
  1311. it with real numbers... you just have to remember that
  1312. i*i = -1
  1313. so you have:
  1314. 5i + 7i = i * (5 + 7) = 12i
  1315. 4i - 3i = i * (4 - 3) = i
  1316. 4i * 2i = -8
  1317. 6i / 2i = 3
  1318. 1 / i = -i
  1319. Complex numbers are numbers that have both a real part and an imaginary
  1320. part, and are usually noted:
  1321. a + bi
  1322. where C<a> is the I<real> part and C<b> is the I<imaginary> part. The
  1323. arithmetic with complex numbers is straightforward. You have to
  1324. keep track of the real and the imaginary parts, but otherwise the
  1325. rules used for real numbers just apply:
  1326. (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
  1327. (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i
  1328. A graphical representation of complex numbers is possible in a plane
  1329. (also called the I<complex plane>, but it's really a 2D plane).
  1330. The number
  1331. z = a + bi
  1332. is the point whose coordinates are (a, b). Actually, it would
  1333. be the vector originating from (0, 0) to (a, b). It follows that the addition
  1334. of two complex numbers is a vectorial addition.
  1335. Since there is a bijection between a point in the 2D plane and a complex
  1336. number (i.e. the mapping is unique and reciprocal), a complex number
  1337. can also be uniquely identified with polar coordinates:
  1338. [rho, theta]
  1339. where C<rho> is the distance to the origin, and C<theta> the angle between
  1340. the vector and the I<x> axis. There is a notation for this using the
  1341. exponential form, which is:
  1342. rho * exp(i * theta)
  1343. where I<i> is the famous imaginary number introduced above. Conversion
  1344. between this form and the cartesian form C<a + bi> is immediate:
  1345. a = rho * cos(theta)
  1346. b = rho * sin(theta)
  1347. which is also expressed by this formula:
  1348. z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)
  1349. In other words, it's the projection of the vector onto the I<x> and I<y>
  1350. axes. Mathematicians call I<rho> the I<norm> or I<modulus> and I<theta>
  1351. the I<argument> of the complex number. The I<norm> of C<z> will be
  1352. noted C<abs(z)>.
  1353. The polar notation (also known as the trigonometric
  1354. representation) is much more handy for performing multiplications and
  1355. divisions of complex numbers, whilst the cartesian notation is better
  1356. suited for additions and subtractions. Real numbers are on the I<x>
  1357. axis, and therefore I<theta> is zero or I<pi>.
  1358. All the common operations that can be performed on a real number have
  1359. been defined to work on complex numbers as well, and are merely
  1360. I<extensions> of the operations defined on real numbers. This means
  1361. they keep their natural meaning when there is no imaginary part, provided
  1362. the number is within their definition set.
  1363. For instance, the C<sqrt> routine which computes the square root of
  1364. its argument is only defined for non-negative real numbers and yields a
  1365. non-negative real number (it is an application from B<R+> to B<R+>).
  1366. If we allow it to return a complex number, then it can be extended to
  1367. negative real numbers to become an application from B<R> to B<C> (the
  1368. set of complex numbers):
  1369. sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i
  1370. It can also be extended to be an application from B<C> to B<C>,
  1371. whilst its restriction to B<R> behaves as defined above by using
  1372. the following definition:
  1373. sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)
  1374. Indeed, a negative real number can be noted C<[x,pi]> (the modulus
  1375. I<x> is always non-negative, so C<[x,pi]> is really C<-x>, a negative
  1376. number) and the above definition states that
  1377. sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i
  1378. which is exactly what we had defined for negative real numbers above.
  1379. The C<sqrt> returns only one of the solutions: if you want the both,
  1380. use the C<root> function.
  1381. All the common mathematical functions defined on real numbers that
  1382. are extended to complex numbers share that same property of working
  1383. I<as usual> when the imaginary part is zero (otherwise, it would not
  1384. be called an extension, would it?).
  1385. A I<new> operation possible on a complex number that is
  1386. the identity for real numbers is called the I<conjugate>, and is noted
  1387. with an horizontal bar above the number, or C<~z> here.
  1388. z = a + bi
  1389. ~z = a - bi
  1390. Simple... Now look:
  1391. z * ~z = (a + bi) * (a - bi) = a*a + b*b
  1392. We saw that the norm of C<z> was noted C<abs(z)> and was defined as the
  1393. distance to the origin, also known as:
  1394. rho = abs(z) = sqrt(a*a + b*b)
  1395. so
  1396. z * ~z = abs(z) ** 2
  1397. If z is a pure real number (i.e. C<b == 0>), then the above yields:
  1398. a * a = abs(a) ** 2
  1399. which is true (C<abs> has the regular meaning for real number, i.e. stands
  1400. for the absolute value). This example explains why the norm of C<z> is
  1401. noted C<abs(z)>: it extends the C<abs> function to complex numbers, yet
  1402. is the regular C<abs> we know when the complex number actually has no
  1403. imaginary part... This justifies I<a posteriori> our use of the C<abs>
  1404. notation for the norm.
  1405. =head1 OPERATIONS
  1406. Given the following notations:
  1407. z1 = a + bi = r1 * exp(i * t1)
  1408. z2 = c + di = r2 * exp(i * t2)
  1409. z = <any complex or real number>
  1410. the following (overloaded) operations are supported on complex numbers:
  1411. z1 + z2 = (a + c) + i(b + d)
  1412. z1 - z2 = (a - c) + i(b - d)
  1413. z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
  1414. z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
  1415. z1 ** z2 = exp(z2 * log z1)
  1416. ~z = a - bi
  1417. abs(z) = r1 = sqrt(a*a + b*b)
  1418. sqrt(z) = sqrt(r1) * exp(i * t/2)
  1419. exp(z) = exp(a) * exp(i * b)
  1420. log(z) = log(r1) + i*t
  1421. sin(z) = 1/2i (exp(i * z1) - exp(-i * z))
  1422. cos(z) = 1/2 (exp(i * z1) + exp(-i * z))
  1423. atan2(z1, z2) = atan(z1/z2)
  1424. The following extra operations are supported on both real and complex
  1425. numbers:
  1426. Re(z) = a
  1427. Im(z) = b
  1428. arg(z) = t
  1429. abs(z) = r
  1430. cbrt(z) = z ** (1/3)
  1431. log10(z) = log(z) / log(10)
  1432. logn(z, n) = log(z) / log(n)
  1433. tan(z) = sin(z) / cos(z)
  1434. csc(z) = 1 / sin(z)
  1435. sec(z) = 1 / cos(z)
  1436. cot(z) = 1 / tan(z)
  1437. asin(z) = -i * log(i*z + sqrt(1-z*z))
  1438. acos(z) = -i * log(z + i*sqrt(1-z*z))
  1439. atan(z) = i/2 * log((i+z) / (i-z))
  1440. acsc(z) = asin(1 / z)
  1441. asec(z) = acos(1 / z)
  1442. acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i))
  1443. sinh(z) = 1/2 (exp(z) - exp(-z))
  1444. cosh(z) = 1/2 (exp(z) + exp(-z))
  1445. tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
  1446. csch(z) = 1 / sinh(z)
  1447. sech(z) = 1 / cosh(z)
  1448. coth(z) = 1 / tanh(z)
  1449. asinh(z) = log(z + sqrt(z*z+1))
  1450. acosh(z) = log(z + sqrt(z*z-1))
  1451. atanh(z) = 1/2 * log((1+z) / (1-z))
  1452. acsch(z) = asinh(1 / z)
  1453. asech(z) = acosh(1 / z)
  1454. acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))
  1455. I<arg>, I<abs>, I<log>, I<csc>, I<cot>, I<acsc>, I<acot>, I<csch>,
  1456. I<coth>, I<acosech>, I<acotanh>, have aliases I<rho>, I<theta>, I<ln>,
  1457. I<cosec>, I<cotan>, I<acosec>, I<acotan>, I<cosech>, I<cotanh>,
  1458. I<acosech>, I<acotanh>, respectively. C<Re>, C<Im>, C<arg>, C<abs>,
  1459. C<rho>, and C<theta> can be used also also mutators. The C<cbrt>
  1460. returns only one of the solutions: if you want all three, use the
  1461. C<root> function.
  1462. The I<root> function is available to compute all the I<n>
  1463. roots of some complex, where I<n> is a strictly positive integer.
  1464. There are exactly I<n> such roots, returned as a list. Getting the
  1465. number mathematicians call C<j> such that:
  1466. 1 + j + j*j = 0;
  1467. is a simple matter of writing:
  1468. $j = ((root(1, 3))[1];
  1469. The I<k>th root for C<z = [r,t]> is given by:
  1470. (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)
  1471. The I<spaceship> comparison operator, E<lt>=E<gt>, is also defined. In
  1472. order to ensure its restriction to real numbers is conform to what you
  1473. would expect, the comparison is run on the real part of the complex
  1474. number first, and imaginary parts are compared only when the real
  1475. parts match.
  1476. =head1 CREATION
  1477. To create a complex number, use either:
  1478. $z = Math::Complex->make(3, 4);
  1479. $z = cplx(3, 4);
  1480. if you know the cartesian form of the number, or
  1481. $z = 3 + 4*i;
  1482. if you like. To create a number using the polar form, use either:
  1483. $z = Math::Complex->emake(5, pi/3);
  1484. $x = cplxe(5, pi/3);
  1485. instead. The first argument is the modulus, the second is the angle
  1486. (in radians, the full circle is 2*pi). (Mnemonic: C<e> is used as a
  1487. notation for complex numbers in the polar form).
  1488. It is possible to write:
  1489. $x = cplxe(-3, pi/4);
  1490. but that will be silently converted into C<[3,-3pi/4]>, since the
  1491. modulus must be non-negative (it represents the distance to the origin
  1492. in the complex plane).
  1493. It is also possible to have a complex number as either argument of
  1494. either the C<make> or C<emake>: the appropriate component of
  1495. the argument will be used.
  1496. $z1 = cplx(-2, 1);
  1497. $z2 = cplx($z1, 4);
  1498. =head1 STRINGIFICATION
  1499. When printed, a complex number is usually shown under its cartesian
  1500. style I<a+bi>, but there are legitimate cases where the polar style
  1501. I<[r,t]> is more appropriate.
  1502. By calling the class method C<Math::Complex::display_format> and
  1503. supplying either C<"polar"> or C<"cartesian"> as an argument, you
  1504. override the default display style, which is C<"cartesian">. Not
  1505. supplying any argument returns the current settings.
  1506. This default can be overridden on a per-number basis by calling the
  1507. C<display_format> method instead. As before, not supplying any argument
  1508. returns the current display style for this number. Otherwise whatever you
  1509. specify will be the new display style for I<this> particular number.
  1510. For instance:
  1511. use Math::Complex;
  1512. Math::Complex::display_format('polar');
  1513. $j = (root(1, 3))[1];
  1514. print "j = $j\n"; # Prints "j = [1,2pi/3]"
  1515. $j->display_format('cartesian');
  1516. print "j = $j\n"; # Prints "j = -0.5+0.866025403784439i"
  1517. The polar style attempts to emphasize arguments like I<k*pi/n>
  1518. (where I<n> is a positive integer and I<k> an integer within [-9, +9]),
  1519. this is called I<polar pretty-printing>.
  1520. =head2 CHANGED IN PERL 5.6
  1521. The C<display_format> class method and the corresponding
  1522. C<display_format> object method can now be called using
  1523. a parameter hash instead of just a one parameter.
  1524. The old display format style, which can have values C<"cartesian"> or
  1525. C<"polar">, can be changed using the C<"style"> parameter.
  1526. $j->display_format(style => "polar");
  1527. The one parameter calling convention also still works.
  1528. $j->display_format("polar");
  1529. There are two new display parameters.
  1530. The first one is C<"format">, which is a sprintf()-style format string
  1531. to be used for both numeric parts of the complex number(s). The is
  1532. somewhat system-dependent but most often it corresponds to C<"%.15g">.
  1533. You can revert to the default by setting the C<format> to C<undef>.
  1534. # the $j from the above example
  1535. $j->display_format('format' => '%.5f');
  1536. print "j = $j\n"; # Prints "j = -0.50000+0.86603i"
  1537. $j->display_format('format' => undef);
  1538. print "j = $j\n"; # Prints "j = -0.5+0.86603i"
  1539. Notice that this affects also the return values of the
  1540. C<display_format> methods: in list context the whole parameter hash
  1541. will be returned, as opposed to only the style parameter value.
  1542. This is a potential incompatibility with earlier versions if you
  1543. have been calling the C<display_format> method in list context.
  1544. The second new display parameter is C<"polar_pretty_print">, which can
  1545. be set to true or false, the default being true. See the previous
  1546. section for what this means.
  1547. =head1 USAGE
  1548. Thanks to overloading, the handling of arithmetics with complex numbers
  1549. is simple and almost transparent.
  1550. Here are some examples:
  1551. use Math::Complex;
  1552. $j = cplxe(1, 2*pi/3); # $j ** 3 == 1
  1553. print "j = $j, j**3 = ", $j ** 3, "\n";
  1554. print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";
  1555. $z = -16 + 0*i; # Force it to be a complex
  1556. print "sqrt($z) = ", sqrt($z), "\n";
  1557. $k = exp(i * 2*pi/3);
  1558. print "$j - $k = ", $j - $k, "\n";
  1559. $z->Re(3); # Re, Im, arg, abs,
  1560. $j->arg(2); # (the last two aka rho, theta)
  1561. # can be used also as mutators.
  1562. =head1 ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO
  1563. The division (/) and the following functions
  1564. log ln log10 logn
  1565. tan sec csc cot
  1566. atan asec acsc acot
  1567. tanh sech csch coth
  1568. atanh asech acsch acoth
  1569. cannot be computed for all arguments because that would mean dividing
  1570. by zero or taking logarithm of zero. These situations cause fatal
  1571. runtime errors looking like this
  1572. cot(0): Division by zero.
  1573. (Because in the definition of cot(0), the divisor sin(0) is 0)
  1574. Died at ...
  1575. or
  1576. atanh(-1): Logarithm of zero.
  1577. Died at...
  1578. For the C<csc>, C<cot>, C<asec>, C<acsc>, C<acot>, C<csch>, C<coth>,
  1579. C<asech>, C<acsch>, the argument cannot be C<0> (zero). For the the
  1580. logarithmic functions and the C<atanh>, C<acoth>, the argument cannot
  1581. be C<1> (one). For the C<atanh>, C<acoth>, the argument cannot be
  1582. C<-1> (minus one). For the C<atan>, C<acot>, the argument cannot be
  1583. C<i> (the imaginary unit). For the C<atan>, C<acoth>, the argument
  1584. cannot be C<-i> (the negative imaginary unit). For the C<tan>,
  1585. C<sec>, C<tanh>, the argument cannot be I<pi/2 + k * pi>, where I<k>
  1586. is any integer.
  1587. Note that because we are operating on approximations of real numbers,
  1588. these errors can happen when merely `too close' to the singularities
  1589. listed above.
  1590. =head1 ERRORS DUE TO INDIGESTIBLE ARGUMENTS
  1591. The C<make> and C<emake> accept both real and complex arguments.
  1592. When they cannot recognize the arguments they will die with error
  1593. messages like the following
  1594. Math::Complex::make: Cannot take real part of ...
  1595. Math::Complex::make: Cannot take real part of ...
  1596. Math::Complex::emake: Cannot take rho of ...
  1597. Math::Complex::emake: Cannot take theta of ...
  1598. =head1 BUGS
  1599. Saying C<use Math::Complex;> exports many mathematical routines in the
  1600. caller environment and even overrides some (C<sqrt>, C<log>).
  1601. This is construed as a feature by the Authors, actually... ;-)
  1602. All routines expect to be given real or complex numbers. Don't attempt to
  1603. use BigFloat, since Perl has currently no rule to disambiguate a '+'
  1604. operation (for instance) between two overloaded entities.
  1605. In Cray UNICOS there is some strange numerical instability that results
  1606. in root(), cos(), sin(), cosh(), sinh(), losing accuracy fast. Beware.
  1607. The bug may be in UNICOS math libs, in UNICOS C compiler, in Math::Complex.
  1608. Whatever it is, it does not manifest itself anywhere else where Perl runs.
  1609. =head1 AUTHORS
  1610. Raphael Manfredi <F<[email protected]>> and
  1611. Jarkko Hietaniemi <F<[email protected]>>.
  1612. Extensive patches by Daniel S. Lewart <F<[email protected]>>.
  1613. =cut
  1614. 1;
  1615. # eof