Java Reference
In-Depth Information
You can also obtain the absolute value for a complex number using the fol-
lowing formula:
a 2
b 2
a
+
bi
= 2
+
(A complex number can be interpreted as a point on a plane by identifying the
( a,b ) values as the coordinates of the point. The absolute value of the complex
number corresponds to the distance of the point to the origin, as shown in Figure
15.12b.)
Design a class named Complex for representing complex numbers and the
methods add , subtract , multiply , divide , and abs for performing complex-
number operations, and override toString method for returning a string
representation for a complex number. The toString method returns (a + bi)
as a string. If b is 0 , it simply returns a .
Provide three constructors Complex(a, b) , Complex(a) , and
Complex() . Complex() creates a Complex object for number 0 and
Complex(a) creates a Complex object with 0 for b . Also provide the
getRealPart() and getImaginaryPart() methods for returning the real
and imaginary part of the complex number, respectively.
Write a test program that prompts the user to enter two complex numbers
and displays the result of their addition, subtraction, multiplication, and divi-
sion. Here is a sample run:
Enter the first complex number:
Enter the second complex number:
(3.5 + 5.5i) + (-3.5 + 1.0i) = 0.0 + 6.5i
(3.5 + 5.5i) - (-3.5 + 1.0i) = 7.0 + 4.5i
(3.5 + 5.5i) * (-3.5 + 1.0i) = -17.75 + -15.75i
(3.5 + 5.5i) / (-3.5 + 1.0i) = -0.5094 + -1.7i
|(3.5 + 5.5i)| = 6.519202405202649
3.5 5.5
-3.5 1
**15.20
( Mandelbrot fractal ) Mandelbrot fractal is a well-known image created from a
Mandelbrot set (see Figure 15.13a). A Mandelbrot set is defined using the fol-
lowing iteration:
z n +
z n + 1 =
c
c is a complex number and the starting point of iteration is For a given
c , the iteration will produce a sequence of complex numbers:
It can be shown that the sequence either tends to infin-
ity or stays bounded, depending on the value of c . For example, if c is 0 , the
sequence is which is bounded. If c is i , the sequence is
which is bounded. If c is the
sequence is which is unbounded. It is known that if
the absolute value of a complex value in the sequence is greater than 2, then
the sequence is unbounded. The Mandelbrot set consists of the c value such
that the sequence is bounded. For example, 0 and i are in the Mandelbrot set. A
Mandelbrot image can be created using the following code:
z 0 =
0.
{ z 0 , z 1 ,
, z n ,
}.
c
c
{0, 0,
},
c
{0, i ,
-
1
+
i ,
-
i ,
-
1
+
i , i ,
},
1
+
i ,
c
{0, 1
+
i , 1
+
3 i ,
},
c
z i
1 class MandelbrotCanvas extends JPanel {
2
final static int COUNT_LIMIT = 60 ;
 
 
Search WWH ::




Custom Search