Source code of Windows XP (NT5)
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.

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