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
13 use vars qw($VERSION @ISA @EXPORT %EXPORT_TAGS);
15 my ( $i, $ip2, %logn );
17 $VERSION = sprintf("%s", q$Id: Complex.pm,v 1.25 1998/02/05 16:07:37 jhi Exp $ =~ /(\d+\.\d+)/);
24 csc cosec sec cot cotan
26 acsc acosec asec acot acotan
28 csch cosech sech coth cotanh
30 acsch acosech asech acoth acotanh
68 my $package = 'Math::Complex'; # Package name
69 my $display = 'cartesian'; # Default display format
70 my $eps = 1e-14; # Epsilon
73 # Object attributes (internal):
74 # cartesian [real, imaginary] -- cartesian form
75 # polar [rho, theta] -- polar form
76 # c_dirty cartesian form not up-to-date
77 # p_dirty polar form not up-to-date
78 # display display format (package's global when not set)
81 # Die on bad *make() arguments.
84 die "@{[(caller(1))[3]]}: Cannot take $_[0] of $_[1].\n";
90 # Create a new complex number (cartesian form)
93 my $self = bless {}, shift;
97 if ( $rre eq ref $self ) {
100 _cannot_make("real part", $rre);
105 if ( $rim eq ref $self ) {
108 _cannot_make("imaginary part", $rim);
111 $self->{'cartesian'} = [ $re, $im ];
112 $self->{c_dirty} = 0;
113 $self->{p_dirty} = 1;
114 $self->display_format('cartesian');
121 # Create a new complex number (exponential form)
124 my $self = bless {}, shift;
125 my ($rho, $theta) = @_;
128 if ( $rrh eq ref $self ) {
131 _cannot_make("rho", $rrh);
134 my $rth = ref $theta;
136 if ( $rth eq ref $self ) {
137 $theta = theta($theta);
139 _cannot_make("theta", $rth);
144 $theta = ($theta <= 0) ? $theta + pi() : $theta - pi();
146 $self->{'polar'} = [$rho, $theta];
147 $self->{p_dirty} = 0;
148 $self->{c_dirty} = 1;
149 $self->display_format('polar');
153 sub new { &make } # For backward compatibility only.
158 # Creates a complex number from a (re, im) tuple.
159 # This avoids the burden of writing Math::Complex->make(re, im).
163 return $package->make($re, defined $im ? $im : 0);
169 # Creates a complex number from a (rho, theta) tuple.
170 # This avoids the burden of writing Math::Complex->emake(rho, theta).
173 my ($rho, $theta) = @_;
174 return $package->emake($rho, defined $theta ? $theta : 0);
180 # The number defined as pi = 180 degrees
182 use constant pi => 4 * atan2(1, 1);
189 use constant pit2 => 2 * pi;
196 use constant pip2 => pi / 2;
203 use constant uplog10 => 1 / log(10);
208 # The number defined as i*i = -1;
213 $i->{'cartesian'} = [0, 1];
214 $i->{'polar'} = [1, pip2];
221 # Attribute access/set routines
224 sub cartesian {$_[0]->{c_dirty} ?
225 $_[0]->update_cartesian : $_[0]->{'cartesian'}}
226 sub polar {$_[0]->{p_dirty} ?
227 $_[0]->update_polar : $_[0]->{'polar'}}
229 sub set_cartesian { $_[0]->{p_dirty}++; $_[0]->{'cartesian'} = $_[1] }
230 sub set_polar { $_[0]->{c_dirty}++; $_[0]->{'polar'} = $_[1] }
235 # Recompute and return the cartesian form, given accurate polar form.
237 sub update_cartesian {
239 my ($r, $t) = @{$self->{'polar'}};
240 $self->{c_dirty} = 0;
241 return $self->{'cartesian'} = [$r * cos $t, $r * sin $t];
248 # Recompute and return the polar form, given accurate cartesian form.
252 my ($x, $y) = @{$self->{'cartesian'}};
253 $self->{p_dirty} = 0;
254 return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
255 return $self->{'polar'} = [sqrt($x*$x + $y*$y), atan2($y, $x)];
264 my ($z1, $z2, $regular) = @_;
265 my ($re1, $im1) = @{$z1->cartesian};
266 $z2 = cplx($z2) unless ref $z2;
267 my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
268 unless (defined $regular) {
269 $z1->set_cartesian([$re1 + $re2, $im1 + $im2]);
272 return (ref $z1)->make($re1 + $re2, $im1 + $im2);
281 my ($z1, $z2, $inverted) = @_;
282 my ($re1, $im1) = @{$z1->cartesian};
283 $z2 = cplx($z2) unless ref $z2;
284 my ($re2, $im2) = @{$z2->cartesian};
285 unless (defined $inverted) {
286 $z1->set_cartesian([$re1 - $re2, $im1 - $im2]);
290 (ref $z1)->make($re2 - $re1, $im2 - $im1) :
291 (ref $z1)->make($re1 - $re2, $im1 - $im2);
301 my ($z1, $z2, $regular) = @_;
302 if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
303 # if both polar better use polar to avoid rounding errors
304 my ($r1, $t1) = @{$z1->polar};
305 my ($r2, $t2) = @{$z2->polar};
307 if ($t > pi()) { $t -= pit2 }
308 elsif ($t <= -pi()) { $t += pit2 }
309 unless (defined $regular) {
310 $z1->set_polar([$r1 * $r2, $t]);
313 return (ref $z1)->emake($r1 * $r2, $t);
315 my ($x1, $y1) = @{$z1->cartesian};
317 my ($x2, $y2) = @{$z2->cartesian};
318 return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2);
320 return (ref $z1)->make($x1*$z2, $y1*$z2);
328 # Die on division by zero.
331 my $mess = "$_[0]: Division by zero.\n";
334 $mess .= "(Because in the definition of $_[0], the divisor ";
335 $mess .= "$_[1] " unless ($_[1] eq '0');
341 $mess .= "Died at $up[1] line $up[2].\n";
352 my ($z1, $z2, $inverted) = @_;
353 if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
354 # if both polar better use polar to avoid rounding errors
355 my ($r1, $t1) = @{$z1->polar};
356 my ($r2, $t2) = @{$z2->polar};
359 _divbyzero "$z2/0" if ($r1 == 0);
361 if ($t > pi()) { $t -= pit2 }
362 elsif ($t <= -pi()) { $t += pit2 }
363 return (ref $z1)->emake($r2 / $r1, $t);
365 _divbyzero "$z1/0" if ($r2 == 0);
367 if ($t > pi()) { $t -= pit2 }
368 elsif ($t <= -pi()) { $t += pit2 }
369 return (ref $z1)->emake($r1 / $r2, $t);
374 ($x2, $y2) = @{$z1->cartesian};
375 $d = $x2*$x2 + $y2*$y2;
376 _divbyzero "$z2/0" if $d == 0;
377 return (ref $z1)->make(($x2*$z2)/$d, -($y2*$z2)/$d);
379 my ($x1, $y1) = @{$z1->cartesian};
381 ($x2, $y2) = @{$z2->cartesian};
382 $d = $x2*$x2 + $y2*$y2;
383 _divbyzero "$z1/0" if $d == 0;
384 my $u = ($x1*$x2 + $y1*$y2)/$d;
385 my $v = ($y1*$x2 - $x1*$y2)/$d;
386 return (ref $z1)->make($u, $v);
388 _divbyzero "$z1/0" if $z2 == 0;
389 return (ref $z1)->make($x1/$z2, $y1/$z2);
398 # Die on zero raised to the zeroth.
401 my $mess = "The zero raised to the zeroth power is not defined.\n";
405 $mess .= "Died at $up[1] line $up[2].\n";
413 # Computes z1**z2 = exp(z2 * log z1)).
416 my ($z1, $z2, $inverted) = @_;
419 _zerotozero if ($z1z and $z2z);
422 return 1 if ($z1z or $z2 == 1);
425 return 1 if ($z2z or $z1 == 1);
427 return $inverted ? exp($z1 * log $z2) : exp($z2 * log $z1);
433 # Computes z1 <=> z2.
434 # Sorts on the real part first, then on the imaginary part. Thus 2-4i > 3+8i.
437 my ($z1, $z2, $inverted) = @_;
438 my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
439 my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
440 my $sgn = $inverted ? -1 : 1;
441 return $sgn * ($re1 <=> $re2) if $re1 != $re2;
442 return $sgn * ($im1 <=> $im2);
453 my ($r, $t) = @{$z->polar};
454 $t = ($t <= 0) ? $t + pi : $t - pi;
455 return (ref $z)->emake($r, $t);
457 my ($re, $im) = @{$z->cartesian};
458 return (ref $z)->make(-$re, -$im);
464 # Compute complex's conjugate.
469 my ($r, $t) = @{$z->polar};
470 return (ref $z)->emake($r, -$t);
472 my ($re, $im) = @{$z->cartesian};
473 return (ref $z)->make($re, -$im);
479 # Compute or set complex's norm (rho).
483 return $z unless ref $z;
485 $z->{'polar'} = [ $rho, ${$z->polar}[1] ];
490 return ${$z->polar}[0];
497 if ($$theta > pi()) { $$theta -= pit2 }
498 elsif ($$theta <= -pi()) { $$theta += pit2 }
504 # Compute or set complex's argument (theta).
507 my ($z, $theta) = @_;
508 return $z unless ref $z;
509 if (defined $theta) {
511 $z->{'polar'} = [ ${$z->polar}[0], $theta ];
515 $theta = ${$z->polar}[1];
526 # It is quite tempting to use wantarray here so that in list context
527 # sqrt() would return the two solutions. This, however, would
530 # print "sqrt(z) = ", sqrt($z), "\n";
532 # The two values would be printed side by side without no intervening
533 # whitespace, quite confusing.
534 # Therefore if you want the two solutions use the root().
538 my ($re, $im) = ref $z ? @{$z->cartesian} : ($z, 0);
539 return $re < 0 ? cplx(0, sqrt(-$re)) : sqrt($re) if $im == 0;
540 my ($r, $t) = @{$z->polar};
541 return (ref $z)->emake(sqrt($r), $t/2);
547 # Compute cbrt(z) (cubic root).
549 # Why are we not returning three values? The same answer as for sqrt().
553 return $z < 0 ? -exp(log(-$z)/3) : ($z > 0 ? exp(log($z)/3): 0)
555 my ($r, $t) = @{$z->polar};
556 return (ref $z)->emake(exp(log($r)/3), $t/3);
565 my $mess = "Root $_[0] not defined, root must be positive integer.\n";
569 $mess .= "Died at $up[1] line $up[2].\n";
577 # Computes all nth root for z, returning an array whose size is n.
578 # `n' must be a positive integer.
580 # The roots are given by (for k = 0..n-1):
582 # z^(1/n) = r^(1/n) (cos ((t+2 k pi)/n) + i sin ((t+2 k pi)/n))
586 _rootbad($n) if ($n < 1 or int($n) != $n);
587 my ($r, $t) = ref $z ? @{$z->polar} : (abs($z), $z >= 0 ? 0 : pi);
590 my $theta_inc = pit2 / $n;
591 my $rho = $r ** (1/$n);
593 my $complex = ref($z) || $package;
594 for ($k = 0, $theta = $t / $n; $k < $n; $k++, $theta += $theta_inc) {
595 push(@root, $complex->emake($rho, $theta));
603 # Return or set Re(z).
607 return $z unless ref $z;
609 $z->{'cartesian'} = [ $Re, ${$z->cartesian}[1] ];
613 return ${$z->cartesian}[0];
620 # Return or set Im(z).
624 return $z unless ref $z;
626 $z->{'cartesian'} = [ ${$z->cartesian}[0], $Im ];
630 return ${$z->cartesian}[1];
637 # Return or set rho(w).
640 Math::Complex::abs(@_);
646 # Return or set theta(w).
649 Math::Complex::arg(@_);
659 my ($x, $y) = @{$z->cartesian};
660 return (ref $z)->emake(exp($x), $y);
666 # Die on logarithm of zero.
669 my $mess = "$_[0]: Logarithm of zero.\n";
672 $mess .= "(Because in the definition of $_[0], the argument ";
673 $mess .= "$_[1] " unless ($_[1] eq '0');
679 $mess .= "Died at $up[1] line $up[2].\n";
692 _logofzero("log") if $z == 0;
693 return $z > 0 ? log($z) : cplx(log(-$z), pi);
695 my ($r, $t) = @{$z->polar};
696 _logofzero("log") if $r == 0;
697 if ($t > pi()) { $t -= pit2 }
698 elsif ($t <= -pi()) { $t += pit2 }
699 return (ref $z)->make(log($r), $t);
707 sub ln { Math::Complex::log(@_) }
716 return Math::Complex::log($_[0]) * uplog10;
722 # Compute logn(z,n) = log(z) / log(n)
726 $z = cplx($z, 0) unless ref $z;
727 my $logn = $logn{$n};
728 $logn = $logn{$n} = log($n) unless defined $logn; # Cache log(n)
729 return log($z) / $logn;
735 # Compute cos(z) = (exp(iz) + exp(-iz))/2.
739 my ($x, $y) = @{$z->cartesian};
742 return (ref $z)->make(cos($x) * ($ey + $ey_1)/2,
743 sin($x) * ($ey_1 - $ey)/2);
749 # Compute sin(z) = (exp(iz) - exp(-iz))/2.
753 my ($x, $y) = @{$z->cartesian};
756 return (ref $z)->make(sin($x) * ($ey + $ey_1)/2,
757 cos($x) * ($ey - $ey_1)/2);
763 # Compute tan(z) = sin(z) / cos(z).
768 _divbyzero "tan($z)", "cos($z)" if (abs($cz) < $eps);
769 return sin($z) / $cz;
775 # Computes the secant sec(z) = 1 / cos(z).
780 _divbyzero "sec($z)", "cos($z)" if ($cz == 0);
787 # Computes the cosecant csc(z) = 1 / sin(z).
792 _divbyzero "csc($z)", "sin($z)" if ($sz == 0);
801 sub cosec { Math::Complex::csc(@_) }
806 # Computes cot(z) = cos(z) / sin(z).
811 _divbyzero "cot($z)", "sin($z)" if ($sz == 0);
812 return cos($z) / $sz;
820 sub cotan { Math::Complex::cot(@_) }
825 # Computes the arc cosine acos(z) = -i log(z + sqrt(z*z-1)).
829 return atan2(sqrt(1-$z*$z), $z) if (! ref $z) && abs($z) <= 1;
830 my ($x, $y) = ref $z ? @{$z->cartesian} : ($z, 0);
831 my $t1 = sqrt(($x+1)*($x+1) + $y*$y);
832 my $t2 = sqrt(($x-1)*($x-1) + $y*$y);
833 my $alpha = ($t1 + $t2)/2;
834 my $beta = ($t1 - $t2)/2;
835 $alpha = 1 if $alpha < 1;
836 if ($beta > 1) { $beta = 1 }
837 elsif ($beta < -1) { $beta = -1 }
838 my $u = atan2(sqrt(1-$beta*$beta), $beta);
839 my $v = log($alpha + sqrt($alpha*$alpha-1));
840 $v = -$v if $y > 0 || ($y == 0 && $x < -1);
841 return $package->make($u, $v);
847 # Computes the arc sine asin(z) = -i log(iz + sqrt(1-z*z)).
851 return atan2($z, sqrt(1-$z*$z)) if (! ref $z) && abs($z) <= 1;
852 my ($x, $y) = ref $z ? @{$z->cartesian} : ($z, 0);
853 my $t1 = sqrt(($x+1)*($x+1) + $y*$y);
854 my $t2 = sqrt(($x-1)*($x-1) + $y*$y);
855 my $alpha = ($t1 + $t2)/2;
856 my $beta = ($t1 - $t2)/2;
857 $alpha = 1 if $alpha < 1;
858 if ($beta > 1) { $beta = 1 }
859 elsif ($beta < -1) { $beta = -1 }
860 my $u = atan2($beta, sqrt(1-$beta*$beta));
861 my $v = -log($alpha + sqrt($alpha*$alpha-1));
862 $v = -$v if $y > 0 || ($y == 0 && $x < -1);
863 return $package->make($u, $v);
869 # Computes the arc tangent atan(z) = i/2 log((i+z) / (i-z)).
873 return atan2($z, 1) unless ref $z;
874 _divbyzero "atan(i)" if ( $z == i);
875 _divbyzero "atan(-i)" if (-$z == i);
876 my $log = log((i + $z) / (i - $z));
877 $ip2 = 0.5 * i unless defined $ip2;
884 # Computes the arc secant asec(z) = acos(1 / z).
888 _divbyzero "asec($z)", $z if ($z == 0);
895 # Computes the arc cosecant acsc(z) = asin(1 / z).
899 _divbyzero "acsc($z)", $z if ($z == 0);
908 sub acosec { Math::Complex::acsc(@_) }
913 # Computes the arc cotangent acot(z) = atan(1 / z)
917 _divbyzero "acot(0)" if (abs($z) < $eps);
918 return ($z >= 0) ? atan2(1, $z) : atan2(-1, -$z) unless ref $z;
919 _divbyzero "acot(i)" if (abs($z - i) < $eps);
920 _logofzero "acot(-i)" if (abs($z + i) < $eps);
929 sub acotan { Math::Complex::acot(@_) }
934 # Computes the hyperbolic cosine cosh(z) = (exp(z) + exp(-z))/2.
941 return ($ex + 1/$ex)/2;
943 my ($x, $y) = @{$z->cartesian};
946 return (ref $z)->make(cos($y) * ($ex + $ex_1)/2,
947 sin($y) * ($ex - $ex_1)/2);
953 # Computes the hyperbolic sine sinh(z) = (exp(z) - exp(-z))/2.
960 return ($ex - 1/$ex)/2;
962 my ($x, $y) = @{$z->cartesian};
965 return (ref $z)->make(cos($y) * ($ex - $ex_1)/2,
966 sin($y) * ($ex + $ex_1)/2);
972 # Computes the hyperbolic tangent tanh(z) = sinh(z) / cosh(z).
977 _divbyzero "tanh($z)", "cosh($z)" if ($cz == 0);
978 return sinh($z) / $cz;
984 # Computes the hyperbolic secant sech(z) = 1 / cosh(z).
989 _divbyzero "sech($z)", "cosh($z)" if ($cz == 0);
996 # Computes the hyperbolic cosecant csch(z) = 1 / sinh(z).
1001 _divbyzero "csch($z)", "sinh($z)" if ($sz == 0);
1010 sub cosech { Math::Complex::csch(@_) }
1015 # Computes the hyperbolic cotangent coth(z) = cosh(z) / sinh(z).
1020 _divbyzero "coth($z)", "sinh($z)" if ($sz == 0);
1021 return cosh($z) / $sz;
1029 sub cotanh { Math::Complex::coth(@_) }
1034 # Computes the arc hyperbolic cosine acosh(z) = log(z + sqrt(z*z-1)).
1039 return log($z + sqrt($z*$z-1)) if $z >= 1;
1042 my ($re, $im) = @{$z->cartesian};
1044 return cplx(log($re + sqrt($re*$re - 1)), 0) if $re >= 1;
1045 return cplx(0, atan2(sqrt(1-$re*$re), $re)) if abs($re) <= 1;
1047 return log($z + sqrt($z*$z - 1));
1053 # Computes the arc hyperbolic sine asinh(z) = log(z + sqrt(z*z-1))
1057 return log($z + sqrt($z*$z + 1));
1063 # Computes the arc hyperbolic tangent atanh(z) = 1/2 log((1+z) / (1-z)).
1068 return log((1 + $z)/(1 - $z))/2 if abs($z) < 1;
1071 _divbyzero 'atanh(1)', "1 - $z" if ($z == 1);
1072 _logofzero 'atanh(-1)' if ($z == -1);
1073 return 0.5 * log((1 + $z) / (1 - $z));
1079 # Computes the hyperbolic arc secant asech(z) = acosh(1 / z).
1083 _divbyzero 'asech(0)', $z if ($z == 0);
1084 return acosh(1 / $z);
1090 # Computes the hyperbolic arc cosecant acsch(z) = asinh(1 / z).
1094 _divbyzero 'acsch(0)', $z if ($z == 0);
1095 return asinh(1 / $z);
1101 # Alias for acosh().
1103 sub acosech { Math::Complex::acsch(@_) }
1108 # Computes the arc hyperbolic cotangent acoth(z) = 1/2 log((1+z) / (z-1)).
1112 _divbyzero 'acoth(0)' if (abs($z) < $eps);
1114 return log(($z + 1)/($z - 1))/2 if abs($z) > 1;
1117 _divbyzero 'acoth(1)', "$z - 1" if (abs($z - 1) < $eps);
1118 _logofzero 'acoth(-1)', "1 / $z" if (abs($z + 1) < $eps);
1119 return log((1 + $z) / ($z - 1)) / 2;
1127 sub acotanh { Math::Complex::acoth(@_) }
1132 # Compute atan(z1/z2).
1135 my ($z1, $z2, $inverted) = @_;
1136 my ($re1, $im1, $re2, $im2);
1138 ($re1, $im1) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
1139 ($re2, $im2) = @{$z1->cartesian};
1141 ($re1, $im1) = @{$z1->cartesian};
1142 ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
1145 return cplx(atan2($re1, $re2), 0) if $im1 == 0;
1146 return cplx(($im1<=>0) * pip2, 0) if $re2 == 0;
1148 my $w = atan($z1/$z2);
1149 my ($u, $v) = ref $w ? @{$w->cartesian} : ($w, 0);
1150 $u += pi if $re2 < 0;
1151 $u -= pit2 if $u > pi;
1152 return cplx($u, $v);
1159 # Set (fetch if no argument) display format for all complex numbers that
1160 # don't happen to have overridden it via ->display_format
1162 # When called as a method, this actually sets the display format for
1163 # the current object.
1165 # Valid object formats are 'c' and 'p' for cartesian and polar. The first
1166 # letter is used actually, so the type can be fully spelled out for clarity.
1168 sub display_format {
1172 if (ref $self) { # Called as a method
1174 } else { # Regular procedure call
1179 if (defined $self) {
1180 return defined $self->{display} ? $self->{display} : $display
1181 unless defined $format;
1182 return $self->{display} = $format;
1185 return $display unless defined $format;
1186 return $display = $format;
1192 # Show nicely formatted complex number under its cartesian or polar form,
1193 # depending on the current display format:
1195 # . If a specific display format has been recorded for this object, use it.
1196 # . Otherwise, use the generic current default for all complex numbers,
1197 # which is a package global variable.
1204 $format = $z->{display} if defined $z->{display};
1206 return $z->stringify_polar if $format =~ /^p/i;
1207 return $z->stringify_cartesian;
1211 # ->stringify_cartesian
1213 # Stringify as a cartesian representation 'a+bi'.
1215 sub stringify_cartesian {
1217 my ($x, $y) = @{$z->cartesian};
1220 $x = int($x + ($x < 0 ? -1 : 1) * $eps)
1221 if int(abs($x)) != int(abs($x) + $eps);
1222 $y = int($y + ($y < 0 ? -1 : 1) * $eps)
1223 if int(abs($y)) != int(abs($y) + $eps);
1225 $re = "$x" if abs($x) >= $eps;
1226 if ($y == 1) { $im = 'i' }
1227 elsif ($y == -1) { $im = '-i' }
1228 elsif (abs($y) >= $eps) { $im = $y . "i" }
1231 $str = $re if defined $re;
1232 $str .= "+$im" if defined $im;
1235 $str = '0' unless $str;
1243 # Stringify as a polar representation '[r,t]'.
1245 sub stringify_polar {
1247 my ($r, $t) = @{$z->polar};
1250 return '[0,0]' if $r <= $eps;
1253 $nt = ($nt - int($nt)) * pit2;
1254 $nt += pit2 if $nt < 0; # Range [0, 2pi]
1256 if (abs($nt) <= $eps) { $theta = 0 }
1257 elsif (abs(pi-$nt) <= $eps) { $theta = 'pi' }
1259 if (defined $theta) {
1260 $r = int($r + ($r < 0 ? -1 : 1) * $eps)
1261 if int(abs($r)) != int(abs($r) + $eps);
1262 $theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
1263 if ($theta ne 'pi' and
1264 int(abs($theta)) != int(abs($theta) + $eps));
1265 return "\[$r,$theta\]";
1269 # Okay, number is not a real. Try to identify pi/n and friends...
1272 $nt -= pit2 if $nt > pi;
1275 for ($k = 1, $kpi = pi; $k < 10; $k++, $kpi += pi) {
1276 $n = int($kpi / $nt + ($nt > 0 ? 1 : -1) * 0.5);
1277 if (abs($kpi/$n - $nt) <= $eps) {
1278 $theta = ($nt < 0 ? '-':'').
1279 ($k == 1 ? 'pi':"${k}pi").'/'.abs($n);
1284 $theta = $nt unless defined $theta;
1286 $r = int($r + ($r < 0 ? -1 : 1) * $eps)
1287 if int(abs($r)) != int(abs($r) + $eps);
1288 $theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
1289 if ($theta !~ m(^-?\d*pi/\d+$) and
1290 int(abs($theta)) != int(abs($theta) + $eps));
1292 return "\[$r,$theta\]";
1300 Math::Complex - complex numbers and associated mathematical functions
1306 $z = Math::Complex->make(5, 6);
1308 $j = cplxe(1, 2*pi/3);
1312 This package lets you create and manipulate complex numbers. By default,
1313 I<Perl> limits itself to real numbers, but an extra C<use> statement brings
1314 full complex support, along with a full set of mathematical functions
1315 typically associated with and/or extended to complex numbers.
1317 If you wonder what complex numbers are, they were invented to be able to solve
1318 the following equation:
1322 and by definition, the solution is noted I<i> (engineers use I<j> instead since
1323 I<i> usually denotes an intensity, but the name does not matter). The number
1324 I<i> is a pure I<imaginary> number.
1326 The arithmetics with pure imaginary numbers works just like you would expect
1327 it with real numbers... you just have to remember that
1333 5i + 7i = i * (5 + 7) = 12i
1334 4i - 3i = i * (4 - 3) = i
1339 Complex numbers are numbers that have both a real part and an imaginary
1340 part, and are usually noted:
1344 where C<a> is the I<real> part and C<b> is the I<imaginary> part. The
1345 arithmetic with complex numbers is straightforward. You have to
1346 keep track of the real and the imaginary parts, but otherwise the
1347 rules used for real numbers just apply:
1349 (4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
1350 (2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i
1352 A graphical representation of complex numbers is possible in a plane
1353 (also called the I<complex plane>, but it's really a 2D plane).
1358 is the point whose coordinates are (a, b). Actually, it would
1359 be the vector originating from (0, 0) to (a, b). It follows that the addition
1360 of two complex numbers is a vectorial addition.
1362 Since there is a bijection between a point in the 2D plane and a complex
1363 number (i.e. the mapping is unique and reciprocal), a complex number
1364 can also be uniquely identified with polar coordinates:
1368 where C<rho> is the distance to the origin, and C<theta> the angle between
1369 the vector and the I<x> axis. There is a notation for this using the
1370 exponential form, which is:
1372 rho * exp(i * theta)
1374 where I<i> is the famous imaginary number introduced above. Conversion
1375 between this form and the cartesian form C<a + bi> is immediate:
1377 a = rho * cos(theta)
1378 b = rho * sin(theta)
1380 which is also expressed by this formula:
1382 z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)
1384 In other words, it's the projection of the vector onto the I<x> and I<y>
1385 axes. Mathematicians call I<rho> the I<norm> or I<modulus> and I<theta>
1386 the I<argument> of the complex number. The I<norm> of C<z> will be
1389 The polar notation (also known as the trigonometric
1390 representation) is much more handy for performing multiplications and
1391 divisions of complex numbers, whilst the cartesian notation is better
1392 suited for additions and subtractions. Real numbers are on the I<x>
1393 axis, and therefore I<theta> is zero or I<pi>.
1395 All the common operations that can be performed on a real number have
1396 been defined to work on complex numbers as well, and are merely
1397 I<extensions> of the operations defined on real numbers. This means
1398 they keep their natural meaning when there is no imaginary part, provided
1399 the number is within their definition set.
1401 For instance, the C<sqrt> routine which computes the square root of
1402 its argument is only defined for non-negative real numbers and yields a
1403 non-negative real number (it is an application from B<R+> to B<R+>).
1404 If we allow it to return a complex number, then it can be extended to
1405 negative real numbers to become an application from B<R> to B<C> (the
1406 set of complex numbers):
1408 sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i
1410 It can also be extended to be an application from B<C> to B<C>,
1411 whilst its restriction to B<R> behaves as defined above by using
1412 the following definition:
1414 sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)
1416 Indeed, a negative real number can be noted C<[x,pi]> (the modulus
1417 I<x> is always non-negative, so C<[x,pi]> is really C<-x>, a negative
1418 number) and the above definition states that
1420 sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i
1422 which is exactly what we had defined for negative real numbers above.
1423 The C<sqrt> returns only one of the solutions: if you want the both,
1424 use the C<root> function.
1426 All the common mathematical functions defined on real numbers that
1427 are extended to complex numbers share that same property of working
1428 I<as usual> when the imaginary part is zero (otherwise, it would not
1429 be called an extension, would it?).
1431 A I<new> operation possible on a complex number that is
1432 the identity for real numbers is called the I<conjugate>, and is noted
1433 with an horizontal bar above the number, or C<~z> here.
1440 z * ~z = (a + bi) * (a - bi) = a*a + b*b
1442 We saw that the norm of C<z> was noted C<abs(z)> and was defined as the
1443 distance to the origin, also known as:
1445 rho = abs(z) = sqrt(a*a + b*b)
1449 z * ~z = abs(z) ** 2
1451 If z is a pure real number (i.e. C<b == 0>), then the above yields:
1455 which is true (C<abs> has the regular meaning for real number, i.e. stands
1456 for the absolute value). This example explains why the norm of C<z> is
1457 noted C<abs(z)>: it extends the C<abs> function to complex numbers, yet
1458 is the regular C<abs> we know when the complex number actually has no
1459 imaginary part... This justifies I<a posteriori> our use of the C<abs>
1460 notation for the norm.
1464 Given the following notations:
1466 z1 = a + bi = r1 * exp(i * t1)
1467 z2 = c + di = r2 * exp(i * t2)
1468 z = <any complex or real number>
1470 the following (overloaded) operations are supported on complex numbers:
1472 z1 + z2 = (a + c) + i(b + d)
1473 z1 - z2 = (a - c) + i(b - d)
1474 z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
1475 z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
1476 z1 ** z2 = exp(z2 * log z1)
1478 abs(z) = r1 = sqrt(a*a + b*b)
1479 sqrt(z) = sqrt(r1) * exp(i * t/2)
1480 exp(z) = exp(a) * exp(i * b)
1481 log(z) = log(r1) + i*t
1482 sin(z) = 1/2i (exp(i * z1) - exp(-i * z))
1483 cos(z) = 1/2 (exp(i * z1) + exp(-i * z))
1484 atan2(z1, z2) = atan(z1/z2)
1486 The following extra operations are supported on both real and complex
1494 cbrt(z) = z ** (1/3)
1495 log10(z) = log(z) / log(10)
1496 logn(z, n) = log(z) / log(n)
1498 tan(z) = sin(z) / cos(z)
1504 asin(z) = -i * log(i*z + sqrt(1-z*z))
1505 acos(z) = -i * log(z + i*sqrt(1-z*z))
1506 atan(z) = i/2 * log((i+z) / (i-z))
1508 acsc(z) = asin(1 / z)
1509 asec(z) = acos(1 / z)
1510 acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i))
1512 sinh(z) = 1/2 (exp(z) - exp(-z))
1513 cosh(z) = 1/2 (exp(z) + exp(-z))
1514 tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))
1516 csch(z) = 1 / sinh(z)
1517 sech(z) = 1 / cosh(z)
1518 coth(z) = 1 / tanh(z)
1520 asinh(z) = log(z + sqrt(z*z+1))
1521 acosh(z) = log(z + sqrt(z*z-1))
1522 atanh(z) = 1/2 * log((1+z) / (1-z))
1524 acsch(z) = asinh(1 / z)
1525 asech(z) = acosh(1 / z)
1526 acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))
1528 I<arg>, I<abs>, I<log>, I<csc>, I<cot>, I<acsc>, I<acot>, I<csch>,
1529 I<coth>, I<acosech>, I<acotanh>, have aliases I<rho>, I<theta>, I<ln>,
1530 I<cosec>, I<cotan>, I<acosec>, I<acotan>, I<cosech>, I<cotanh>,
1531 I<acosech>, I<acotanh>, respectively. C<Re>, C<Im>, C<arg>, C<abs>,
1532 C<rho>, and C<theta> can be used also also mutators. The C<cbrt>
1533 returns only one of the solutions: if you want all three, use the
1536 The I<root> function is available to compute all the I<n>
1537 roots of some complex, where I<n> is a strictly positive integer.
1538 There are exactly I<n> such roots, returned as a list. Getting the
1539 number mathematicians call C<j> such that:
1543 is a simple matter of writing:
1545 $j = ((root(1, 3))[1];
1547 The I<k>th root for C<z = [r,t]> is given by:
1549 (root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)
1551 The I<spaceship> comparison operator, E<lt>=E<gt>, is also defined. In
1552 order to ensure its restriction to real numbers is conform to what you
1553 would expect, the comparison is run on the real part of the complex
1554 number first, and imaginary parts are compared only when the real
1559 To create a complex number, use either:
1561 $z = Math::Complex->make(3, 4);
1564 if you know the cartesian form of the number, or
1568 if you like. To create a number using the polar form, use either:
1570 $z = Math::Complex->emake(5, pi/3);
1571 $x = cplxe(5, pi/3);
1573 instead. The first argument is the modulus, the second is the angle
1574 (in radians, the full circle is 2*pi). (Mnemonic: C<e> is used as a
1575 notation for complex numbers in the polar form).
1577 It is possible to write:
1579 $x = cplxe(-3, pi/4);
1581 but that will be silently converted into C<[3,-3pi/4]>, since the modulus
1582 must be non-negative (it represents the distance to the origin in the complex
1585 It is also possible to have a complex number as either argument of
1586 either the C<make> or C<emake>: the appropriate component of
1587 the argument will be used.
1592 =head1 STRINGIFICATION
1594 When printed, a complex number is usually shown under its cartesian
1595 form I<a+bi>, but there are legitimate cases where the polar format
1596 I<[r,t]> is more appropriate.
1598 By calling the routine C<Math::Complex::display_format> and supplying either
1599 C<"polar"> or C<"cartesian">, you override the default display format,
1600 which is C<"cartesian">. Not supplying any argument returns the current
1603 This default can be overridden on a per-number basis by calling the
1604 C<display_format> method instead. As before, not supplying any argument
1605 returns the current display format for this number. Otherwise whatever you
1606 specify will be the new display format for I<this> particular number.
1612 Math::Complex::display_format('polar');
1613 $j = ((root(1, 3))[1];
1614 print "j = $j\n"; # Prints "j = [1,2pi/3]
1615 $j->display_format('cartesian');
1616 print "j = $j\n"; # Prints "j = -0.5+0.866025403784439i"
1618 The polar format attempts to emphasize arguments like I<k*pi/n>
1619 (where I<n> is a positive integer and I<k> an integer within [-9,+9]).
1623 Thanks to overloading, the handling of arithmetics with complex numbers
1624 is simple and almost transparent.
1626 Here are some examples:
1630 $j = cplxe(1, 2*pi/3); # $j ** 3 == 1
1631 print "j = $j, j**3 = ", $j ** 3, "\n";
1632 print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";
1634 $z = -16 + 0*i; # Force it to be a complex
1635 print "sqrt($z) = ", sqrt($z), "\n";
1637 $k = exp(i * 2*pi/3);
1638 print "$j - $k = ", $j - $k, "\n";
1640 $z->Re(3); # Re, Im, arg, abs,
1641 $j->arg(2); # (the last two aka rho, theta)
1642 # can be used also as mutators.
1644 =head1 ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO
1646 The division (/) and the following functions
1652 atanh asech acsch acoth
1654 cannot be computed for all arguments because that would mean dividing
1655 by zero or taking logarithm of zero. These situations cause fatal
1656 runtime errors looking like this
1658 cot(0): Division by zero.
1659 (Because in the definition of cot(0), the divisor sin(0) is 0)
1664 atanh(-1): Logarithm of zero.
1667 For the C<csc>, C<cot>, C<asec>, C<acsc>, C<acot>, C<csch>, C<coth>,
1668 C<asech>, C<acsch>, the argument cannot be C<0> (zero). For the the
1669 logarithmic functions and the C<atanh>, C<acoth>, the argument cannot
1670 be C<1> (one). For the C<atanh>, C<acoth>, the argument cannot be
1671 C<-1> (minus one). For the C<atan>, C<acot>, the argument cannot be
1672 C<i> (the imaginary unit). For the C<atan>, C<acoth>, the argument
1673 cannot be C<-i> (the negative imaginary unit). For the C<tan>,
1674 C<sec>, C<tanh>, the argument cannot be I<pi/2 + k * pi>, where I<k>
1677 Note that because we are operating on approximations of real numbers,
1678 these errors can happen when merely `too close' to the singularities
1679 listed above. For example C<tan(2*atan2(1,1)+1e-15)> will die of
1682 =head1 ERRORS DUE TO INDIGESTIBLE ARGUMENTS
1684 The C<make> and C<emake> accept both real and complex arguments.
1685 When they cannot recognize the arguments they will die with error
1686 messages like the following
1688 Math::Complex::make: Cannot take real part of ...
1689 Math::Complex::make: Cannot take real part of ...
1690 Math::Complex::emake: Cannot take rho of ...
1691 Math::Complex::emake: Cannot take theta of ...
1695 Saying C<use Math::Complex;> exports many mathematical routines in the
1696 caller environment and even overrides some (C<sqrt>, C<log>).
1697 This is construed as a feature by the Authors, actually... ;-)
1699 All routines expect to be given real or complex numbers. Don't attempt to
1700 use BigFloat, since Perl has currently no rule to disambiguate a '+'
1701 operation (for instance) between two overloaded entities.
1705 Raphael Manfredi <F<Raphael_Manfredi@grenoble.hp.com>> and
1706 Jarkko Hietaniemi <F<jhi@iki.fi>>.
1708 Extensive patches by Daniel S. Lewart <F<d-lewart@uiuc.edu>>.