1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 package org.apache.commons.math.complex;
19
20 import org.apache.commons.math.TestUtils;
21
22 import junit.framework.TestCase;
23
24
25
26
27 public class ComplexUtilsTest extends TestCase {
28
29 private double inf = Double.POSITIVE_INFINITY;
30 private double negInf = Double.NEGATIVE_INFINITY;
31 private double nan = Double.NaN;
32 private double pi = Math.PI;
33
34 private Complex negInfInf = new Complex(negInf, inf);
35 private Complex infNegInf = new Complex(inf, negInf);
36 private Complex infInf = new Complex(inf, inf);
37 private Complex negInfNegInf = new Complex(negInf, negInf);
38 private Complex infNaN = new Complex(inf, nan);
39
40 public void testPolar2Complex() {
41 TestUtils.assertEquals(Complex.ONE,
42 ComplexUtils.polar2Complex(1, 0), 10e-12);
43 TestUtils.assertEquals(Complex.ZERO,
44 ComplexUtils.polar2Complex(0, 1), 10e-12);
45 TestUtils.assertEquals(Complex.ZERO,
46 ComplexUtils.polar2Complex(0, -1), 10e-12);
47 TestUtils.assertEquals(Complex.I,
48 ComplexUtils.polar2Complex(1, pi/2), 10e-12);
49 TestUtils.assertEquals(Complex.I.negate(),
50 ComplexUtils.polar2Complex(1, -pi/2), 10e-12);
51 double r = 0;
52 for (int i = 0; i < 5; i++) {
53 r += i;
54 double theta = 0;
55 for (int j =0; j < 20; j++) {
56 theta += pi / 6;
57 TestUtils.assertEquals(altPolar(r, theta),
58 ComplexUtils.polar2Complex(r, theta), 10e-12);
59 }
60 theta = -2 * pi;
61 for (int j =0; j < 20; j++) {
62 theta -= pi / 6;
63 TestUtils.assertEquals(altPolar(r, theta),
64 ComplexUtils.polar2Complex(r, theta), 10e-12);
65 }
66 }
67 }
68
69 protected Complex altPolar(double r, double theta) {
70 return Complex.I.multiply(new Complex(theta, 0)).exp().multiply(new Complex(r, 0));
71 }
72
73 public void testPolar2ComplexIllegalModulus() {
74 try {
75 ComplexUtils.polar2Complex(-1, 0);
76 fail("Expecting IllegalArgumentException");
77 } catch (IllegalArgumentException ex) {
78
79 }
80 }
81
82 public void testPolar2ComplexNaN() {
83 TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(nan, 1));
84 TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(1, nan));
85 TestUtils.assertSame(Complex.NaN,
86 ComplexUtils.polar2Complex(nan, nan));
87 }
88
89 public void testPolar2ComplexInf() {
90 TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(1, inf));
91 TestUtils.assertSame(Complex.NaN,
92 ComplexUtils.polar2Complex(1, negInf));
93 TestUtils.assertSame(Complex.NaN, ComplexUtils.polar2Complex(inf, inf));
94 TestUtils.assertSame(Complex.NaN,
95 ComplexUtils.polar2Complex(inf, negInf));
96 TestUtils.assertSame(infInf, ComplexUtils.polar2Complex(inf, pi/4));
97 TestUtils.assertSame(infNaN, ComplexUtils.polar2Complex(inf, 0));
98 TestUtils.assertSame(infNegInf, ComplexUtils.polar2Complex(inf, -pi/4));
99 TestUtils.assertSame(negInfInf, ComplexUtils.polar2Complex(inf, 3*pi/4));
100 TestUtils.assertSame(negInfNegInf, ComplexUtils.polar2Complex(inf, 5*pi/4));
101 }
102
103 }