summaryrefslogtreecommitdiff
path: root/lib/Math/Complex.pm
blob: aca85c6acd08268bf62497e3160a01cfdaf41e78 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
#
# Complex numbers and associated mathematical functions
# -- Raphael Manfredi	Since Sep 1996
# -- Jarkko Hietaniemi	Since Mar 1997
# -- Daniel S. Lewart	Since Sep 1997
#

require Exporter;
package Math::Complex;

use strict;

use vars qw($VERSION @ISA @EXPORT %EXPORT_TAGS);

my ( $i, $ip2, %logn );

$VERSION = sprintf("%s", q$Id: Complex.pm,v 1.25 1998/02/05 16:07:37 jhi Exp $ =~ /(\d+\.\d+)/);

@ISA = qw(Exporter);

my @trig = qw(
	      pi
	      tan
	      csc cosec sec cot cotan
	      asin acos atan
	      acsc acosec asec acot acotan
	      sinh cosh tanh
	      csch cosech sech coth cotanh
	      asinh acosh atanh
	      acsch acosech asech acoth acotanh
	     );

@EXPORT = (qw(
	     i Re Im rho theta arg
	     sqrt log ln
	     log10 logn cbrt root
	     cplx cplxe
	     ),
	   @trig);

%EXPORT_TAGS = (
    'trig' => [@trig],
);

use overload
	'+'	=> \&plus,
	'-'	=> \&minus,
	'*'	=> \&multiply,
	'/'	=> \&divide,
	'**'	=> \&power,
	'<=>'	=> \&spaceship,
	'neg'	=> \&negate,
	'~'	=> \&conjugate,
	'abs'	=> \&abs,
	'sqrt'	=> \&sqrt,
	'exp'	=> \&exp,
	'log'	=> \&log,
	'sin'	=> \&sin,
	'cos'	=> \&cos,
	'tan'	=> \&tan,
	'atan2'	=> \&atan2,
	qw("" stringify);

#
# Package "privates"
#

my $package = 'Math::Complex';		# Package name
my $display = 'cartesian';		# Default display format
my $eps     = 1e-14;			# Epsilon

#
# Object attributes (internal):
#	cartesian	[real, imaginary] -- cartesian form
#	polar		[rho, theta] -- polar form
#	c_dirty		cartesian form not up-to-date
#	p_dirty		polar form not up-to-date
#	display		display format (package's global when not set)
#

# Die on bad *make() arguments.

sub _cannot_make {
    die "@{[(caller(1))[3]]}: Cannot take $_[0] of $_[1].\n";
}

#
# ->make
#
# Create a new complex number (cartesian form)
#
sub make {
	my $self = bless {}, shift;
	my ($re, $im) = @_;
	my $rre = ref $re;
	if ( $rre ) {
	    if ( $rre eq ref $self ) {
		$re = Re($re);
	    } else {
		_cannot_make("real part", $rre);
	    }
	}
	my $rim = ref $im;
	if ( $rim ) {
	    if ( $rim eq ref $self ) {
		$im = Im($im);
	    } else {
		_cannot_make("imaginary part", $rim);
	    }
	}
	$self->{'cartesian'} = [ $re, $im ];
	$self->{c_dirty} = 0;
	$self->{p_dirty} = 1;
	$self->display_format('cartesian');
	return $self;
}

#
# ->emake
#
# Create a new complex number (exponential form)
#
sub emake {
	my $self = bless {}, shift;
	my ($rho, $theta) = @_;
	my $rrh = ref $rho;
	if ( $rrh ) {
	    if ( $rrh eq ref $self ) {
		$rho = rho($rho);
	    } else {
		_cannot_make("rho", $rrh);
	    }
	}
	my $rth = ref $theta;
	if ( $rth ) {
	    if ( $rth eq ref $self ) {
		$theta = theta($theta);
	    } else {
		_cannot_make("theta", $rth);
	    }
	}
	if ($rho < 0) {
	    $rho   = -$rho;
	    $theta = ($theta <= 0) ? $theta + pi() : $theta - pi();
	}
	$self->{'polar'} = [$rho, $theta];
	$self->{p_dirty} = 0;
	$self->{c_dirty} = 1;
	$self->display_format('polar');
	return $self;
}

sub new { &make }		# For backward compatibility only.

#
# cplx
#
# Creates a complex number from a (re, im) tuple.
# This avoids the burden of writing Math::Complex->make(re, im).
#
sub cplx {
	my ($re, $im) = @_;
	return $package->make($re, defined $im ? $im : 0);
}

#
# cplxe
#
# Creates a complex number from a (rho, theta) tuple.
# This avoids the burden of writing Math::Complex->emake(rho, theta).
#
sub cplxe {
	my ($rho, $theta) = @_;
	return $package->emake($rho, defined $theta ? $theta : 0);
}

#
# pi
#
# The number defined as pi = 180 degrees
#
use constant pi => 4 * atan2(1, 1);

#
# pit2
#
# The full circle
#
use constant pit2 => 2 * pi;

#
# pip2
#
# The quarter circle
#
use constant pip2 => pi / 2;

#
# deg1
#
# One degree in radians, used in stringify_polar.
#

use constant deg1 => pi / 180;

#
# uplog10
#
# Used in log10().
#
use constant uplog10 => 1 / log(10);

#
# i
#
# The number defined as i*i = -1;
#
sub i () {
        return $i if ($i);
	$i = bless {};
	$i->{'cartesian'} = [0, 1];
	$i->{'polar'}     = [1, pip2];
	$i->{c_dirty} = 0;
	$i->{p_dirty} = 0;
	return $i;
}

#
# Attribute access/set routines
#

sub cartesian {$_[0]->{c_dirty} ?
		   $_[0]->update_cartesian : $_[0]->{'cartesian'}}
sub polar     {$_[0]->{p_dirty} ?
		   $_[0]->update_polar : $_[0]->{'polar'}}

sub set_cartesian { $_[0]->{p_dirty}++; $_[0]->{'cartesian'} = $_[1] }
sub set_polar     { $_[0]->{c_dirty}++; $_[0]->{'polar'} = $_[1] }

#
# ->update_cartesian
#
# Recompute and return the cartesian form, given accurate polar form.
#
sub update_cartesian {
	my $self = shift;
	my ($r, $t) = @{$self->{'polar'}};
	$self->{c_dirty} = 0;
	return $self->{'cartesian'} = [$r * cos $t, $r * sin $t];
}

#
#
# ->update_polar
#
# Recompute and return the polar form, given accurate cartesian form.
#
sub update_polar {
	my $self = shift;
	my ($x, $y) = @{$self->{'cartesian'}};
	$self->{p_dirty} = 0;
	return $self->{'polar'} = [0, 0] if $x == 0 && $y == 0;
	return $self->{'polar'} = [sqrt($x*$x + $y*$y), atan2($y, $x)];
}

#
# (plus)
#
# Computes z1+z2.
#
sub plus {
	my ($z1, $z2, $regular) = @_;
	my ($re1, $im1) = @{$z1->cartesian};
	$z2 = cplx($z2) unless ref $z2;
	my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
	unless (defined $regular) {
		$z1->set_cartesian([$re1 + $re2, $im1 + $im2]);
		return $z1;
	}
	return (ref $z1)->make($re1 + $re2, $im1 + $im2);
}

#
# (minus)
#
# Computes z1-z2.
#
sub minus {
	my ($z1, $z2, $inverted) = @_;
	my ($re1, $im1) = @{$z1->cartesian};
	$z2 = cplx($z2) unless ref $z2;
	my ($re2, $im2) = @{$z2->cartesian};
	unless (defined $inverted) {
		$z1->set_cartesian([$re1 - $re2, $im1 - $im2]);
		return $z1;
	}
	return $inverted ?
		(ref $z1)->make($re2 - $re1, $im2 - $im1) :
		(ref $z1)->make($re1 - $re2, $im1 - $im2);

}

#
# (multiply)
#
# Computes z1*z2.
#
sub multiply {
        my ($z1, $z2, $regular) = @_;
	if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
	    # if both polar better use polar to avoid rounding errors
	    my ($r1, $t1) = @{$z1->polar};
	    my ($r2, $t2) = @{$z2->polar};
	    my $t = $t1 + $t2;
	    if    ($t >   pi()) { $t -= pit2 }
	    elsif ($t <= -pi()) { $t += pit2 }
	    unless (defined $regular) {
		$z1->set_polar([$r1 * $r2, $t]);
		return $z1;
	    }
	    return (ref $z1)->emake($r1 * $r2, $t);
	} else {
	    my ($x1, $y1) = @{$z1->cartesian};
	    if (ref $z2) {
		my ($x2, $y2) = @{$z2->cartesian};
		return (ref $z1)->make($x1*$x2-$y1*$y2, $x1*$y2+$y1*$x2);
	    } else {
		return (ref $z1)->make($x1*$z2, $y1*$z2);
	    }
	}
}

#
# _divbyzero
#
# Die on division by zero.
#
sub _divbyzero {
    my $mess = "$_[0]: Division by zero.\n";

    if (defined $_[1]) {
	$mess .= "(Because in the definition of $_[0], the divisor ";
	$mess .= "$_[1] " unless ($_[1] eq '0');
	$mess .= "is 0)\n";
    }

    my @up = caller(1);

    $mess .= "Died at $up[1] line $up[2].\n";

    die $mess;
}

#
# (divide)
#
# Computes z1/z2.
#
sub divide {
	my ($z1, $z2, $inverted) = @_;
	if ($z1->{p_dirty} == 0 and ref $z2 and $z2->{p_dirty} == 0) {
	    # if both polar better use polar to avoid rounding errors
	    my ($r1, $t1) = @{$z1->polar};
	    my ($r2, $t2) = @{$z2->polar};
	    my $t;
	    if ($inverted) {
		_divbyzero "$z2/0" if ($r1 == 0);
		$t = $t2 - $t1;
		if    ($t >   pi()) { $t -= pit2 }
		elsif ($t <= -pi()) { $t += pit2 }
		return (ref $z1)->emake($r2 / $r1, $t);
	    } else {
		_divbyzero "$z1/0" if ($r2 == 0);
		$t = $t1 - $t2;
		if    ($t >   pi()) { $t -= pit2 }
		elsif ($t <= -pi()) { $t += pit2 }
		return (ref $z1)->emake($r1 / $r2, $t);
	    }
	} else {
	    my ($d, $x2, $y2);
	    if ($inverted) {
		($x2, $y2) = @{$z1->cartesian};
		$d = $x2*$x2 + $y2*$y2;
		_divbyzero "$z2/0" if $d == 0;
		return (ref $z1)->make(($x2*$z2)/$d, -($y2*$z2)/$d);
	    } else {
		my ($x1, $y1) = @{$z1->cartesian};
		if (ref $z2) {
		    ($x2, $y2) = @{$z2->cartesian};
		    $d = $x2*$x2 + $y2*$y2;
		    _divbyzero "$z1/0" if $d == 0;
		    my $u = ($x1*$x2 + $y1*$y2)/$d;
		    my $v = ($y1*$x2 - $x1*$y2)/$d;
		    return (ref $z1)->make($u, $v);
		} else {
		    _divbyzero "$z1/0" if $z2 == 0;
		    return (ref $z1)->make($x1/$z2, $y1/$z2);
		}
	    }
	}
}

#
# _zerotozero
#
# Die on zero raised to the zeroth.
#
sub _zerotozero {
    my $mess = "The zero raised to the zeroth power is not defined.\n";

    my @up = caller(1);

    $mess .= "Died at $up[1] line $up[2].\n";

    die $mess;
}

#
# (power)
#
# Computes z1**z2 = exp(z2 * log z1)).
#
sub power {
	my ($z1, $z2, $inverted) = @_;
	my $z1z = $z1 == 0;
	my $z2z = $z2 == 0;
	_zerotozero if ($z1z and $z2z);
	if ($inverted) {
	    return 0 if ($z2z);
	    return 1 if ($z1z or $z2 == 1);
	} else {
	    return 0 if ($z1z);
	    return 1 if ($z2z or $z1 == 1);
	}
	my $w = $inverted ? exp($z1 * log $z2) : exp($z2 * log $z1);
	# If both arguments cartesian, return cartesian, else polar.
	return $z1->{c_dirty} == 0 &&
	       (not ref $z2 or $z2->{c_dirty} == 0) ?
	       cplx(@{$w->cartesian}) : $w;
}

#
# (spaceship)
#
# Computes z1 <=> z2.
# Sorts on the real part first, then on the imaginary part. Thus 2-4i > 3+8i.
#
sub spaceship {
	my ($z1, $z2, $inverted) = @_;
	my ($re1, $im1) = ref $z1 ? @{$z1->cartesian} : ($z1, 0);
	my ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
	my $sgn = $inverted ? -1 : 1;
	return $sgn * ($re1 <=> $re2) if $re1 != $re2;
	return $sgn * ($im1 <=> $im2);
}

#
# (negate)
#
# Computes -z.
#
sub negate {
	my ($z) = @_;
	if ($z->{c_dirty}) {
		my ($r, $t) = @{$z->polar};
		$t = ($t <= 0) ? $t + pi : $t - pi;
		return (ref $z)->emake($r, $t);
	}
	my ($re, $im) = @{$z->cartesian};
	return (ref $z)->make(-$re, -$im);
}

#
# (conjugate)
#
# Compute complex's conjugate.
#
sub conjugate {
	my ($z) = @_;
	if ($z->{c_dirty}) {
		my ($r, $t) = @{$z->polar};
		return (ref $z)->emake($r, -$t);
	}
	my ($re, $im) = @{$z->cartesian};
	return (ref $z)->make($re, -$im);
}

#
# (abs)
#
# Compute or set complex's norm (rho).
#
sub abs {
	my ($z, $rho) = @_;
	return $z unless ref $z;
	if (defined $rho) {
	    $z->{'polar'} = [ $rho, ${$z->polar}[1] ];
	    $z->{p_dirty} = 0;
	    $z->{c_dirty} = 1;
	    return $rho;
	} else {
	    return ${$z->polar}[0];
	}
}

sub _theta {
    my $theta = $_[0];

    if    ($$theta >   pi()) { $$theta -= pit2 }
    elsif ($$theta <= -pi()) { $$theta += pit2 }
}

#
# arg
#
# Compute or set complex's argument (theta).
#
sub arg {
	my ($z, $theta) = @_;
	return $z unless ref $z;
	if (defined $theta) {
	    _theta(\$theta);
	    $z->{'polar'} = [ ${$z->polar}[0], $theta ];
	    $z->{p_dirty} = 0;
	    $z->{c_dirty} = 1;
	} else {
	    $theta = ${$z->polar}[1];
	    _theta(\$theta);
	}
	return $theta;
}

#
# (sqrt)
#
# Compute sqrt(z).
#
# It is quite tempting to use wantarray here so that in list context
# sqrt() would return the two solutions.  This, however, would
# break things like
#
#	print "sqrt(z) = ", sqrt($z), "\n";
#
# The two values would be printed side by side without no intervening
# whitespace, quite confusing.
# Therefore if you want the two solutions use the root().
#
sub sqrt {
	my ($z) = @_;
	my ($re, $im) = ref $z ? @{$z->cartesian} : ($z, 0);
	return $re < 0 ? cplx(0, sqrt(-$re)) : sqrt($re) if $im == 0;
	my ($r, $t) = @{$z->polar};
	return (ref $z)->emake(sqrt($r), $t/2);
}

#
# cbrt
#
# Compute cbrt(z) (cubic root).
#
# Why are we not returning three values?  The same answer as for sqrt().
#
sub cbrt {
	my ($z) = @_;
	return $z < 0 ? -exp(log(-$z)/3) : ($z > 0 ? exp(log($z)/3): 0)
	    unless ref $z;
	my ($r, $t) = @{$z->polar};
	return (ref $z)->emake(exp(log($r)/3), $t/3);
}

#
# _rootbad
#
# Die on bad root.
#
sub _rootbad {
    my $mess = "Root $_[0] not defined, root must be positive integer.\n";

    my @up = caller(1);

    $mess .= "Died at $up[1] line $up[2].\n";

    die $mess;
}

#
# root
#
# Computes all nth root for z, returning an array whose size is n.
# `n' must be a positive integer.
#
# The roots are given by (for k = 0..n-1):
#
# z^(1/n) = r^(1/n) (cos ((t+2 k pi)/n) + i sin ((t+2 k pi)/n))
#
sub root {
	my ($z, $n) = @_;
	_rootbad($n) if ($n < 1 or int($n) != $n);
	my ($r, $t) = ref $z ? @{$z->polar} : (abs($z), $z >= 0 ? 0 : pi);
	my @root;
	my $k;
	my $theta_inc = pit2 / $n;
	my $rho = $r ** (1/$n);
	my $theta;
	my $cartesian = ref $z && $z->{c_dirty} == 0;
	for ($k = 0, $theta = $t / $n; $k < $n; $k++, $theta += $theta_inc) {
	    my $w = cplxe($rho, $theta);
	    # Yes, $cartesian is loop invariant.
	    push @root, $cartesian ? cplx(@{$w->cartesian}) : $w;
	}
	return @root;
}

#
# Re
#
# Return or set Re(z).
#
sub Re {
	my ($z, $Re) = @_;
	return $z unless ref $z;
	if (defined $Re) {
	    $z->{'cartesian'} = [ $Re, ${$z->cartesian}[1] ];
	    $z->{c_dirty} = 0;
	    $z->{p_dirty} = 1;
	} else {
	    return ${$z->cartesian}[0];
	}
}

#
# Im
#
# Return or set Im(z).
#
sub Im {
	my ($z, $Im) = @_;
	return $z unless ref $z;
	if (defined $Im) {
	    $z->{'cartesian'} = [ ${$z->cartesian}[0], $Im ];
	    $z->{c_dirty} = 0;
	    $z->{p_dirty} = 1;
	} else {
	    return ${$z->cartesian}[1];
	}
}

#
# rho
#
# Return or set rho(w).
#
sub rho {
    Math::Complex::abs(@_);
}

#
# theta
#
# Return or set theta(w).
#
sub theta {
    Math::Complex::arg(@_);
}

#
# (exp)
#
# Computes exp(z).
#
sub exp {
	my ($z) = @_;
	my ($x, $y) = @{$z->cartesian};
	return (ref $z)->emake(exp($x), $y);
}

#
# _logofzero
#
# Die on logarithm of zero.
#
sub _logofzero {
    my $mess = "$_[0]: Logarithm of zero.\n";

    if (defined $_[1]) {
	$mess .= "(Because in the definition of $_[0], the argument ";
	$mess .= "$_[1] " unless ($_[1] eq '0');
	$mess .= "is 0)\n";
    }

    my @up = caller(1);

    $mess .= "Died at $up[1] line $up[2].\n";

    die $mess;
}

#
# (log)
#
# Compute log(z).
#
sub log {
	my ($z) = @_;
	unless (ref $z) {
	    _logofzero("log") if $z == 0;
	    return $z > 0 ? log($z) : cplx(log(-$z), pi);
	}
	my ($r, $t) = @{$z->polar};
	_logofzero("log") if $r == 0;
	if    ($t >   pi()) { $t -= pit2 }
	elsif ($t <= -pi()) { $t += pit2 }
	return (ref $z)->make(log($r), $t);
}

#
# ln
#
# Alias for log().
#
sub ln { Math::Complex::log(@_) }

#
# log10
#
# Compute log10(z).
#

sub log10 {
	return Math::Complex::log($_[0]) * uplog10;
}

#
# logn
#
# Compute logn(z,n) = log(z) / log(n)
#
sub logn {
	my ($z, $n) = @_;
	$z = cplx($z, 0) unless ref $z;
	my $logn = $logn{$n};
	$logn = $logn{$n} = log($n) unless defined $logn;	# Cache log(n)
	return log($z) / $logn;
}

#
# (cos)
#
# Compute cos(z) = (exp(iz) + exp(-iz))/2.
#
sub cos {
	my ($z) = @_;
	my ($x, $y) = @{$z->cartesian};
	my $ey = exp($y);
	my $ey_1 = 1 / $ey;
	return (ref $z)->make(cos($x) * ($ey + $ey_1)/2,
			      sin($x) * ($ey_1 - $ey)/2);
}

#
# (sin)
#
# Compute sin(z) = (exp(iz) - exp(-iz))/2.
#
sub sin {
	my ($z) = @_;
	my ($x, $y) = @{$z->cartesian};
	my $ey = exp($y);
	my $ey_1 = 1 / $ey;
	return (ref $z)->make(sin($x) * ($ey + $ey_1)/2,
			      cos($x) * ($ey - $ey_1)/2);
}

#
# tan
#
# Compute tan(z) = sin(z) / cos(z).
#
sub tan {
	my ($z) = @_;
	my $cz = cos($z);
	_divbyzero "tan($z)", "cos($z)" if (abs($cz) < $eps);
	return sin($z) / $cz;
}

#
# sec
#
# Computes the secant sec(z) = 1 / cos(z).
#
sub sec {
	my ($z) = @_;
	my $cz = cos($z);
	_divbyzero "sec($z)", "cos($z)" if ($cz == 0);
	return 1 / $cz;
}

#
# csc
#
# Computes the cosecant csc(z) = 1 / sin(z).
#
sub csc {
	my ($z) = @_;
	my $sz = sin($z);
	_divbyzero "csc($z)", "sin($z)" if ($sz == 0);
	return 1 / $sz;
}

#
# cosec
#
# Alias for csc().
#
sub cosec { Math::Complex::csc(@_) }

#
# cot
#
# Computes cot(z) = cos(z) / sin(z).
#
sub cot {
	my ($z) = @_;
	my $sz = sin($z);
	_divbyzero "cot($z)", "sin($z)" if ($sz == 0);
	return cos($z) / $sz;
}

#
# cotan
#
# Alias for cot().
#
sub cotan { Math::Complex::cot(@_) }

#
# acos
#
# Computes the arc cosine acos(z) = -i log(z + sqrt(z*z-1)).
#
sub acos {
	my $z = $_[0];
	return atan2(sqrt(1-$z*$z), $z) if (! ref $z) && abs($z) <= 1;
	my ($x, $y) = ref $z ? @{$z->cartesian} : ($z, 0);
	my $t1 = sqrt(($x+1)*($x+1) + $y*$y);
	my $t2 = sqrt(($x-1)*($x-1) + $y*$y);
	my $alpha = ($t1 + $t2)/2;
	my $beta  = ($t1 - $t2)/2;
	$alpha = 1 if $alpha < 1;
	if    ($beta >  1) { $beta =  1 }
	elsif ($beta < -1) { $beta = -1 }
	my $u = atan2(sqrt(1-$beta*$beta), $beta);
	my $v = log($alpha + sqrt($alpha*$alpha-1));
	$v = -$v if $y > 0 || ($y == 0 && $x < -1);
	return $package->make($u, $v);
}

#
# asin
#
# Computes the arc sine asin(z) = -i log(iz + sqrt(1-z*z)).
#
sub asin {
	my $z = $_[0];
	return atan2($z, sqrt(1-$z*$z)) if (! ref $z) && abs($z) <= 1;
	my ($x, $y) = ref $z ? @{$z->cartesian} : ($z, 0);
	my $t1 = sqrt(($x+1)*($x+1) + $y*$y);
	my $t2 = sqrt(($x-1)*($x-1) + $y*$y);
	my $alpha = ($t1 + $t2)/2;
	my $beta  = ($t1 - $t2)/2;
	$alpha = 1 if $alpha < 1;
	if    ($beta >  1) { $beta =  1 }
	elsif ($beta < -1) { $beta = -1 }
	my $u =  atan2($beta, sqrt(1-$beta*$beta));
	my $v = -log($alpha + sqrt($alpha*$alpha-1));
	$v = -$v if $y > 0 || ($y == 0 && $x < -1);
	return $package->make($u, $v);
}

#
# atan
#
# Computes the arc tangent atan(z) = i/2 log((i+z) / (i-z)).
#
sub atan {
	my ($z) = @_;
	return atan2($z, 1) unless ref $z;
	_divbyzero "atan(i)"  if ( $z == i);
	_divbyzero "atan(-i)" if (-$z == i);
	my $log = log((i + $z) / (i - $z));
	$ip2 = 0.5 * i unless defined $ip2;
	return $ip2 * $log;
}

#
# asec
#
# Computes the arc secant asec(z) = acos(1 / z).
#
sub asec {
	my ($z) = @_;
	_divbyzero "asec($z)", $z if ($z == 0);
	return acos(1 / $z);
}

#
# acsc
#
# Computes the arc cosecant acsc(z) = asin(1 / z).
#
sub acsc {
	my ($z) = @_;
	_divbyzero "acsc($z)", $z if ($z == 0);
	return asin(1 / $z);
}

#
# acosec
#
# Alias for acsc().
#
sub acosec { Math::Complex::acsc(@_) }

#
# acot
#
# Computes the arc cotangent acot(z) = atan(1 / z)
#
sub acot {
	my ($z) = @_;
	_divbyzero "acot(0)"  if (abs($z)     < $eps);
	return ($z >= 0) ? atan2(1, $z) : atan2(-1, -$z) unless ref $z;
	_divbyzero "acot(i)"  if (abs($z - i) < $eps);
	_logofzero "acot(-i)" if (abs($z + i) < $eps);
	return atan(1 / $z);
}

#
# acotan
#
# Alias for acot().
#
sub acotan { Math::Complex::acot(@_) }

#
# cosh
#
# Computes the hyperbolic cosine cosh(z) = (exp(z) + exp(-z))/2.
#
sub cosh {
	my ($z) = @_;
	my $ex;
	unless (ref $z) {
	    $ex = exp($z);
	    return ($ex + 1/$ex)/2;
	}
	my ($x, $y) = @{$z->cartesian};
	$ex = exp($x);
	my $ex_1 = 1 / $ex;
	return (ref $z)->make(cos($y) * ($ex + $ex_1)/2,
			      sin($y) * ($ex - $ex_1)/2);
}

#
# sinh
#
# Computes the hyperbolic sine sinh(z) = (exp(z) - exp(-z))/2.
#
sub sinh {
	my ($z) = @_;
	my $ex;
	unless (ref $z) {
	    $ex = exp($z);
	    return ($ex - 1/$ex)/2;
	}
	my ($x, $y) = @{$z->cartesian};
	$ex = exp($x);
	my $ex_1 = 1 / $ex;
	return (ref $z)->make(cos($y) * ($ex - $ex_1)/2,
			      sin($y) * ($ex + $ex_1)/2);
}

#
# tanh
#
# Computes the hyperbolic tangent tanh(z) = sinh(z) / cosh(z).
#
sub tanh {
	my ($z) = @_;
	my $cz = cosh($z);
	_divbyzero "tanh($z)", "cosh($z)" if ($cz == 0);
	return sinh($z) / $cz;
}

#
# sech
#
# Computes the hyperbolic secant sech(z) = 1 / cosh(z).
#
sub sech {
	my ($z) = @_;
	my $cz = cosh($z);
	_divbyzero "sech($z)", "cosh($z)" if ($cz == 0);
	return 1 / $cz;
}

#
# csch
#
# Computes the hyperbolic cosecant csch(z) = 1 / sinh(z).
#
sub csch {
	my ($z) = @_;
	my $sz = sinh($z);
	_divbyzero "csch($z)", "sinh($z)" if ($sz == 0);
	return 1 / $sz;
}

#
# cosech
#
# Alias for csch().
#
sub cosech { Math::Complex::csch(@_) }

#
# coth
#
# Computes the hyperbolic cotangent coth(z) = cosh(z) / sinh(z).
#
sub coth {
	my ($z) = @_;
	my $sz = sinh($z);
	_divbyzero "coth($z)", "sinh($z)" if ($sz == 0);
	return cosh($z) / $sz;
}

#
# cotanh
#
# Alias for coth().
#
sub cotanh { Math::Complex::coth(@_) }

#
# acosh
#
# Computes the arc hyperbolic cosine acosh(z) = log(z + sqrt(z*z-1)).
#
sub acosh {
	my ($z) = @_;
	unless (ref $z) {
	    return log($z + sqrt($z*$z-1)) if $z >= 1;
	    $z = cplx($z, 0);
	}
	my ($re, $im) = @{$z->cartesian};
	if ($im == 0) {
	    return cplx(log($re + sqrt($re*$re - 1)), 0) if $re >= 1;
	    return cplx(0, atan2(sqrt(1-$re*$re), $re)) if abs($re) <= 1;
	}
	return log($z + sqrt($z*$z - 1));
}

#
# asinh
#
# Computes the arc hyperbolic sine asinh(z) = log(z + sqrt(z*z-1))
#
sub asinh {
	my ($z) = @_;
	return log($z + sqrt($z*$z + 1));
}

#
# atanh
#
# Computes the arc hyperbolic tangent atanh(z) = 1/2 log((1+z) / (1-z)).
#
sub atanh {
	my ($z) = @_;
	unless (ref $z) {
	    return log((1 + $z)/(1 - $z))/2 if abs($z) < 1;
	    $z = cplx($z, 0);
	}
	_divbyzero 'atanh(1)',  "1 - $z" if ($z ==  1);
	_logofzero 'atanh(-1)'           if ($z == -1);
	return 0.5 * log((1 + $z) / (1 - $z));
}

#
# asech
#
# Computes the hyperbolic arc secant asech(z) = acosh(1 / z).
#
sub asech {
	my ($z) = @_;
	_divbyzero 'asech(0)', $z if ($z == 0);
	return acosh(1 / $z);
}

#
# acsch
#
# Computes the hyperbolic arc cosecant acsch(z) = asinh(1 / z).
#
sub acsch {
	my ($z) = @_;
	_divbyzero 'acsch(0)', $z if ($z == 0);
	return asinh(1 / $z);
}

#
# acosech
#
# Alias for acosh().
#
sub acosech { Math::Complex::acsch(@_) }

#
# acoth
#
# Computes the arc hyperbolic cotangent acoth(z) = 1/2 log((1+z) / (z-1)).
#
sub acoth {
	my ($z) = @_;
	_divbyzero 'acoth(0)'            if (abs($z)     < $eps);
	unless (ref $z) {
	    return log(($z + 1)/($z - 1))/2 if abs($z) > 1;
	    $z = cplx($z, 0);
	}
	_divbyzero 'acoth(1)',  "$z - 1" if (abs($z - 1) < $eps);
	_logofzero 'acoth(-1)', "1 / $z" if (abs($z + 1) < $eps);
	return log((1 + $z) / ($z - 1)) / 2;
}

#
# acotanh
#
# Alias for acot().
#
sub acotanh { Math::Complex::acoth(@_) }

#
# (atan2)
#
# Compute atan(z1/z2).
#
sub atan2 {
	my ($z1, $z2, $inverted) = @_;
	my ($re1, $im1, $re2, $im2);
	if ($inverted) {
	    ($re1, $im1) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
	    ($re2, $im2) = @{$z1->cartesian};
	} else {
	    ($re1, $im1) = @{$z1->cartesian};
	    ($re2, $im2) = ref $z2 ? @{$z2->cartesian} : ($z2, 0);
	}
	if ($im2 == 0) {
	    return cplx(atan2($re1, $re2), 0) if $im1 == 0;
	    return cplx(($im1<=>0) * pip2, 0) if $re2 == 0;
	}
	my $w = atan($z1/$z2);
	my ($u, $v) = ref $w ? @{$w->cartesian} : ($w, 0);
	$u += pi   if $re2 < 0;
	$u -= pit2 if $u > pi;
	return cplx($u, $v);
}

#
# display_format
# ->display_format
#
# Set (fetch if no argument) display format for all complex numbers that
# don't happen to have overridden it via ->display_format
#
# When called as a method, this actually sets the display format for
# the current object.
#
# Valid object formats are 'c' and 'p' for cartesian and polar. The first
# letter is used actually, so the type can be fully spelled out for clarity.
#
sub display_format {
	my $self = shift;
	my $format = undef;

	if (ref $self) {			# Called as a method
		$format = shift;
	} else {				# Regular procedure call
		$format = $self;
		undef $self;
	}

	if (defined $self) {
		return defined $self->{display} ? $self->{display} : $display
			unless defined $format;
		return $self->{display} = $format;
	}

	return $display unless defined $format;
	return $display = $format;
}

#
# (stringify)
#
# Show nicely formatted complex number under its cartesian or polar form,
# depending on the current display format:
#
# . If a specific display format has been recorded for this object, use it.
# . Otherwise, use the generic current default for all complex numbers,
#   which is a package global variable.
#
sub stringify {
	my ($z) = shift;
	my $format;

	$format = $display;
	$format = $z->{display} if defined $z->{display};

	return $z->stringify_polar if $format =~ /^p/i;
	return $z->stringify_cartesian;
}

#
# ->stringify_cartesian
#
# Stringify as a cartesian representation 'a+bi'.
#
sub stringify_cartesian {
	my $z  = shift;
	my ($x, $y) = @{$z->cartesian};
	my ($re, $im);

	$x = int($x + ($x < 0 ? -1 : 1) * $eps)
		if int(abs($x)) != int(abs($x) + $eps);
	$y = int($y + ($y < 0 ? -1 : 1) * $eps)
		if int(abs($y)) != int(abs($y) + $eps);

	$re = "$x" if abs($x) >= $eps;
        if ($y == 1)                           { $im = 'i' }
        elsif ($y == -1)                       { $im = '-i' }
        elsif (abs($y) >= $eps)                { $im = $y . "i" }

	my $str = '';
	$str = $re if defined $re;
	$str .= "+$im" if defined $im;
	$str =~ s/\+-/-/;
	$str =~ s/^\+//;
	$str =~ s/([-+])1i/$1i/; # Not redundant with the above 1/-1 tests.
	$str = '0' unless $str;

	return $str;
}


# Helper for stringify_polar, a Greatest Common Divisor with a memory.

sub _gcd {
    my ($a, $b) = @_;

    use integer;

    # Loops forever if given negative inputs.

    if    ($b and $a > $b) { return gcd($a % $b, $b) }
    elsif ($a and $b > $a) { return gcd($b % $a, $a) }
    else                   { return $a ? $a : $b     }
}

my %gcd;

sub gcd {
    my ($a, $b) = @_;

    my $id = "$a $b";
    
    unless (exists $gcd{$id}) {
	$gcd{$id} = _gcd($a, $b);
	$gcd{"$b $a"} = $gcd{$id};
    }

    return $gcd{$id};
}

#
# ->stringify_polar
#
# Stringify as a polar representation '[r,t]'.
#
sub stringify_polar {
	my $z  = shift;
	my ($r, $t) = @{$z->polar};
	my $theta;

	return '[0,0]' if $r <= $eps;

	my $nt = $t / pit2;
	$nt = ($nt - int($nt)) * pit2;
	$nt += pit2 if $nt < 0;			# Range [0, 2pi]

	if (abs($nt) <= $eps)		{ $theta = 0 }
	elsif (abs(pi-$nt) <= $eps)	{ $theta = 'pi' }

	if (defined $theta) {
		$r = int($r + ($r < 0 ? -1 : 1) * $eps)
			if int(abs($r)) != int(abs($r) + $eps);
		$theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
			if ($theta ne 'pi' and
			    int(abs($theta)) != int(abs($theta) + $eps));
		return "\[$r,$theta\]";
	}

	#
	# Okay, number is not a real. Try to identify pi/n and friends...
	#

	$nt -= pit2 if $nt > pi;

	if (abs($nt) >= deg1) {
	    my ($n, $k, $kpi);

	    for ($k = 1, $kpi = pi; $k < 10; $k++, $kpi += pi) {
		$n = int($kpi / $nt + ($nt > 0 ? 1 : -1) * 0.5);
		if (abs($kpi/$n - $nt) <= $eps) {
		    $n = abs $n;
		    my $gcd = gcd($k, $n);
		    if ($gcd > 1) {
			$k /= $gcd;
			$n /= $gcd;
		    }
		    next if $n > 360;
		    $theta = ($nt < 0 ? '-':'').
			     ($k == 1 ? 'pi':"${k}pi");
		    $theta .= '/'.$n if $n > 1;
		    last;
		}
	    }
	}

	$theta = $nt unless defined $theta;

	$r = int($r + ($r < 0 ? -1 : 1) * $eps)
		if int(abs($r)) != int(abs($r) + $eps);
	$theta = int($theta + ($theta < 0 ? -1 : 1) * $eps)
		if ($theta !~ m(^-?\d*pi/\d+$) and
		    int(abs($theta)) != int(abs($theta) + $eps));

	return "\[$r,$theta\]";
}

1;
__END__

=head1 NAME

Math::Complex - complex numbers and associated mathematical functions

=head1 SYNOPSIS

	use Math::Complex;

	$z = Math::Complex->make(5, 6);
	$t = 4 - 3*i + $z;
	$j = cplxe(1, 2*pi/3);

=head1 DESCRIPTION

This package lets you create and manipulate complex numbers. By default,
I<Perl> limits itself to real numbers, but an extra C<use> statement brings
full complex support, along with a full set of mathematical functions
typically associated with and/or extended to complex numbers.

If you wonder what complex numbers are, they were invented to be able to solve
the following equation:

	x*x = -1

and by definition, the solution is noted I<i> (engineers use I<j> instead since
I<i> usually denotes an intensity, but the name does not matter). The number
I<i> is a pure I<imaginary> number.

The arithmetics with pure imaginary numbers works just like you would expect
it with real numbers... you just have to remember that

	i*i = -1

so you have:

	5i + 7i = i * (5 + 7) = 12i
	4i - 3i = i * (4 - 3) = i
	4i * 2i = -8
	6i / 2i = 3
	1 / i = -i

Complex numbers are numbers that have both a real part and an imaginary
part, and are usually noted:

	a + bi

where C<a> is the I<real> part and C<b> is the I<imaginary> part. The
arithmetic with complex numbers is straightforward. You have to
keep track of the real and the imaginary parts, but otherwise the
rules used for real numbers just apply:

	(4 + 3i) + (5 - 2i) = (4 + 5) + i(3 - 2) = 9 + i
	(2 + i) * (4 - i) = 2*4 + 4i -2i -i*i = 8 + 2i + 1 = 9 + 2i

A graphical representation of complex numbers is possible in a plane
(also called the I<complex plane>, but it's really a 2D plane).
The number

	z = a + bi

is the point whose coordinates are (a, b). Actually, it would
be the vector originating from (0, 0) to (a, b). It follows that the addition
of two complex numbers is a vectorial addition.

Since there is a bijection between a point in the 2D plane and a complex
number (i.e. the mapping is unique and reciprocal), a complex number
can also be uniquely identified with polar coordinates:

	[rho, theta]

where C<rho> is the distance to the origin, and C<theta> the angle between
the vector and the I<x> axis. There is a notation for this using the
exponential form, which is:

	rho * exp(i * theta)

where I<i> is the famous imaginary number introduced above. Conversion
between this form and the cartesian form C<a + bi> is immediate:

	a = rho * cos(theta)
	b = rho * sin(theta)

which is also expressed by this formula:

	z = rho * exp(i * theta) = rho * (cos theta + i * sin theta)

In other words, it's the projection of the vector onto the I<x> and I<y>
axes. Mathematicians call I<rho> the I<norm> or I<modulus> and I<theta>
the I<argument> of the complex number. The I<norm> of C<z> will be
noted C<abs(z)>.

The polar notation (also known as the trigonometric
representation) is much more handy for performing multiplications and
divisions of complex numbers, whilst the cartesian notation is better
suited for additions and subtractions. Real numbers are on the I<x>
axis, and therefore I<theta> is zero or I<pi>.

All the common operations that can be performed on a real number have
been defined to work on complex numbers as well, and are merely
I<extensions> of the operations defined on real numbers. This means
they keep their natural meaning when there is no imaginary part, provided
the number is within their definition set.

For instance, the C<sqrt> routine which computes the square root of
its argument is only defined for non-negative real numbers and yields a
non-negative real number (it is an application from B<R+> to B<R+>).
If we allow it to return a complex number, then it can be extended to
negative real numbers to become an application from B<R> to B<C> (the
set of complex numbers):

	sqrt(x) = x >= 0 ? sqrt(x) : sqrt(-x)*i

It can also be extended to be an application from B<C> to B<C>,
whilst its restriction to B<R> behaves as defined above by using
the following definition:

	sqrt(z = [r,t]) = sqrt(r) * exp(i * t/2)

Indeed, a negative real number can be noted C<[x,pi]> (the modulus
I<x> is always non-negative, so C<[x,pi]> is really C<-x>, a negative
number) and the above definition states that

	sqrt([x,pi]) = sqrt(x) * exp(i*pi/2) = [sqrt(x),pi/2] = sqrt(x)*i

which is exactly what we had defined for negative real numbers above.
The C<sqrt> returns only one of the solutions: if you want the both,
use the C<root> function.

All the common mathematical functions defined on real numbers that
are extended to complex numbers share that same property of working
I<as usual> when the imaginary part is zero (otherwise, it would not
be called an extension, would it?).

A I<new> operation possible on a complex number that is
the identity for real numbers is called the I<conjugate>, and is noted
with an horizontal bar above the number, or C<~z> here.

	 z = a + bi
	~z = a - bi

Simple... Now look:

	z * ~z = (a + bi) * (a - bi) = a*a + b*b

We saw that the norm of C<z> was noted C<abs(z)> and was defined as the
distance to the origin, also known as:

	rho = abs(z) = sqrt(a*a + b*b)

so

	z * ~z = abs(z) ** 2

If z is a pure real number (i.e. C<b == 0>), then the above yields:

	a * a = abs(a) ** 2

which is true (C<abs> has the regular meaning for real number, i.e. stands
for the absolute value). This example explains why the norm of C<z> is
noted C<abs(z)>: it extends the C<abs> function to complex numbers, yet
is the regular C<abs> we know when the complex number actually has no
imaginary part... This justifies I<a posteriori> our use of the C<abs>
notation for the norm.

=head1 OPERATIONS

Given the following notations:

	z1 = a + bi = r1 * exp(i * t1)
	z2 = c + di = r2 * exp(i * t2)
	z = <any complex or real number>

the following (overloaded) operations are supported on complex numbers:

	z1 + z2 = (a + c) + i(b + d)
	z1 - z2 = (a - c) + i(b - d)
	z1 * z2 = (r1 * r2) * exp(i * (t1 + t2))
	z1 / z2 = (r1 / r2) * exp(i * (t1 - t2))
	z1 ** z2 = exp(z2 * log z1)
	~z = a - bi
	abs(z) = r1 = sqrt(a*a + b*b)
	sqrt(z) = sqrt(r1) * exp(i * t/2)
	exp(z) = exp(a) * exp(i * b)
	log(z) = log(r1) + i*t
	sin(z) = 1/2i (exp(i * z1) - exp(-i * z))
	cos(z) = 1/2 (exp(i * z1) + exp(-i * z))
	atan2(z1, z2) = atan(z1/z2)

The following extra operations are supported on both real and complex
numbers:

	Re(z) = a
	Im(z) = b
	arg(z) = t
	abs(z) = r

	cbrt(z) = z ** (1/3)
	log10(z) = log(z) / log(10)
	logn(z, n) = log(z) / log(n)

	tan(z) = sin(z) / cos(z)

	csc(z) = 1 / sin(z)
	sec(z) = 1 / cos(z)
	cot(z) = 1 / tan(z)

	asin(z) = -i * log(i*z + sqrt(1-z*z))
	acos(z) = -i * log(z + i*sqrt(1-z*z))
	atan(z) = i/2 * log((i+z) / (i-z))

	acsc(z) = asin(1 / z)
	asec(z) = acos(1 / z)
	acot(z) = atan(1 / z) = -i/2 * log((i+z) / (z-i))

	sinh(z) = 1/2 (exp(z) - exp(-z))
	cosh(z) = 1/2 (exp(z) + exp(-z))
	tanh(z) = sinh(z) / cosh(z) = (exp(z) - exp(-z)) / (exp(z) + exp(-z))

	csch(z) = 1 / sinh(z)
	sech(z) = 1 / cosh(z)
	coth(z) = 1 / tanh(z)

	asinh(z) = log(z + sqrt(z*z+1))
	acosh(z) = log(z + sqrt(z*z-1))
	atanh(z) = 1/2 * log((1+z) / (1-z))

	acsch(z) = asinh(1 / z)
	asech(z) = acosh(1 / z)
	acoth(z) = atanh(1 / z) = 1/2 * log((1+z) / (z-1))

I<arg>, I<abs>, I<log>, I<csc>, I<cot>, I<acsc>, I<acot>, I<csch>,
I<coth>, I<acosech>, I<acotanh>, have aliases I<rho>, I<theta>, I<ln>,
I<cosec>, I<cotan>, I<acosec>, I<acotan>, I<cosech>, I<cotanh>,
I<acosech>, I<acotanh>, respectively.  C<Re>, C<Im>, C<arg>, C<abs>,
C<rho>, and C<theta> can be used also also mutators.  The C<cbrt>
returns only one of the solutions: if you want all three, use the
C<root> function.

The I<root> function is available to compute all the I<n>
roots of some complex, where I<n> is a strictly positive integer.
There are exactly I<n> such roots, returned as a list. Getting the
number mathematicians call C<j> such that:

	1 + j + j*j = 0;

is a simple matter of writing:

	$j = ((root(1, 3))[1];

The I<k>th root for C<z = [r,t]> is given by:

	(root(z, n))[k] = r**(1/n) * exp(i * (t + 2*k*pi)/n)

The I<spaceship> comparison operator, E<lt>=E<gt>, is also defined. In
order to ensure its restriction to real numbers is conform to what you
would expect, the comparison is run on the real part of the complex
number first, and imaginary parts are compared only when the real
parts match.

=head1 CREATION

To create a complex number, use either:

	$z = Math::Complex->make(3, 4);
	$z = cplx(3, 4);

if you know the cartesian form of the number, or

	$z = 3 + 4*i;

if you like. To create a number using the polar form, use either:

	$z = Math::Complex->emake(5, pi/3);
	$x = cplxe(5, pi/3);

instead. The first argument is the modulus, the second is the angle
(in radians, the full circle is 2*pi).  (Mnemonic: C<e> is used as a
notation for complex numbers in the polar form).

It is possible to write:

	$x = cplxe(-3, pi/4);

but that will be silently converted into C<[3,-3pi/4]>, since the modulus
must be non-negative (it represents the distance to the origin in the complex
plane).

It is also possible to have a complex number as either argument of
either the C<make> or C<emake>: the appropriate component of
the argument will be used.

	$z1 = cplx(-2,  1);
	$z2 = cplx($z1, 4);

=head1 STRINGIFICATION

When printed, a complex number is usually shown under its cartesian
form I<a+bi>, but there are legitimate cases where the polar format
I<[r,t]> is more appropriate.

By calling the routine C<Math::Complex::display_format> and supplying either
C<"polar"> or C<"cartesian">, you override the default display format,
which is C<"cartesian">. Not supplying any argument returns the current
setting.

This default can be overridden on a per-number basis by calling the
C<display_format> method instead. As before, not supplying any argument
returns the current display format for this number. Otherwise whatever you
specify will be the new display format for I<this> particular number.

For instance:

	use Math::Complex;

	Math::Complex::display_format('polar');
	$j = ((root(1, 3))[1];
	print "j = $j\n";		# Prints "j = [1,2pi/3]
	$j->display_format('cartesian');
	print "j = $j\n";		# Prints "j = -0.5+0.866025403784439i"

The polar format attempts to emphasize arguments like I<k*pi/n>
(where I<n> is a positive integer and I<k> an integer within [-9,+9]).

=head1 USAGE

Thanks to overloading, the handling of arithmetics with complex numbers
is simple and almost transparent.

Here are some examples:

	use Math::Complex;

	$j = cplxe(1, 2*pi/3);	# $j ** 3 == 1
	print "j = $j, j**3 = ", $j ** 3, "\n";
	print "1 + j + j**2 = ", 1 + $j + $j**2, "\n";

	$z = -16 + 0*i;			# Force it to be a complex
	print "sqrt($z) = ", sqrt($z), "\n";

	$k = exp(i * 2*pi/3);
	print "$j - $k = ", $j - $k, "\n";

	$z->Re(3);			# Re, Im, arg, abs,
	$j->arg(2);			# (the last two aka rho, theta)
					# can be used also as mutators.

=head1 ERRORS DUE TO DIVISION BY ZERO OR LOGARITHM OF ZERO

The division (/) and the following functions

	log	ln	log10	logn
	tan	sec 	csc	cot
	atan	asec	acsc	acot
	tanh	sech	csch	coth
	atanh	asech	acsch	acoth

cannot be computed for all arguments because that would mean dividing
by zero or taking logarithm of zero. These situations cause fatal
runtime errors looking like this

	cot(0): Division by zero.
	(Because in the definition of cot(0), the divisor sin(0) is 0)
	Died at ...

or

	atanh(-1): Logarithm of zero.
	Died at...

For the C<csc>, C<cot>, C<asec>, C<acsc>, C<acot>, C<csch>, C<coth>,
C<asech>, C<acsch>, the argument cannot be C<0> (zero).  For the the
logarithmic functions and the C<atanh>, C<acoth>, the argument cannot
be C<1> (one).  For the C<atanh>, C<acoth>, the argument cannot be
C<-1> (minus one).  For the C<atan>, C<acot>, the argument cannot be
C<i> (the imaginary unit).  For the C<atan>, C<acoth>, the argument
cannot be C<-i> (the negative imaginary unit).  For the C<tan>,
C<sec>, C<tanh>, the argument cannot be I<pi/2 + k * pi>, where I<k>
is any integer.

Note that because we are operating on approximations of real numbers,
these errors can happen when merely `too close' to the singularities
listed above.  For example C<tan(2*atan2(1,1)+1e-15)> will die of
division by zero.

=head1 ERRORS DUE TO INDIGESTIBLE ARGUMENTS

The C<make> and C<emake> accept both real and complex arguments.
When they cannot recognize the arguments they will die with error
messages like the following

    Math::Complex::make: Cannot take real part of ...
    Math::Complex::make: Cannot take real part of ...
    Math::Complex::emake: Cannot take rho of ...
    Math::Complex::emake: Cannot take theta of ...

=head1 BUGS

Saying C<use Math::Complex;> exports many mathematical routines in the
caller environment and even overrides some (C<sqrt>, C<log>).
This is construed as a feature by the Authors, actually... ;-)

All routines expect to be given real or complex numbers. Don't attempt to
use BigFloat, since Perl has currently no rule to disambiguate a '+'
operation (for instance) between two overloaded entities.

In Cray UNICOS there is some strange numerical instability that results
in root(), cos(), sin(), cosh(), sinh(), losing accuracy fast.  Beware.
The bug may be in UNICOS math libs, in UNICOS C compiler, in Math::Complex.
Whatever it is, it does not manifest itself anywhere else where Perl runs.

=head1 AUTHORS

Raphael Manfredi <F<Raphael_Manfredi@grenoble.hp.com>> and
Jarkko Hietaniemi <F<jhi@iki.fi>>.

Extensive patches by Daniel S. Lewart <F<d-lewart@uiuc.edu>>.

=cut

1;

# eof