Perl Cookbook

Perl CookbookSearch this book
Previous: 2.14. Multiplying MatricesChapter 2
Numbers
Next: 2.16. Converting Between Octal and Hexadecimal
 

2.15. Using Complex Numbers

Problem

Your application must manipulate complex numbers, as are often needed in engineering, science, and mathematics.

Solution

Either keep track of the real and imaginary components yourself, or use the Math::Complex class (part of the standard Perl distribution).

Manually

# $c = $a * $b manually
$c_real = ( $a_real * $b_real ) - ( $a_imaginary * $b_imaginary );
$c_imaginary = ( $a_real * $b_imaginary ) + ( $b_real * $a_imaginary );

Math::Complex

# $c = $a * $b using Math::Complex
use Math::Complex;
$c = $a * $b;

Discussion

Here's how you'd manually multiply 3+5i and 2-2i:

$a_real = 3; $a_imaginary = 5;              # 3 + 5i;
$b_real = 2; $b_imaginary = -2;             # 2 - 2i;
$c_real = ( $a_real * $b_real ) - ( $a_imaginary * $b_imaginary );
$c_imaginary = ( $a_real * $b_imaginary ) + ( $b_real * $a_imaginary );
print "c = ${c_real}+${c_imaginary}i\n";

c = 16+4i

and with Math::Complex:

use Math::Complex;
$a = Math::Complex->new(3,5);               # or Math::Complex->new(3,5);
$b = Math::Complex->new(2,-2);
$c = $a * $b;
print "c = $c\n";

c = 16+4i

With the 5.004 version, you may create complex numbers via the cplx constructor or via the exported constant i :

use Math::Complex;
$c = cplx(3,5) * cplx(2,-2);                # easier on the eye
$d = 3 + 4*i;                               # 3 + 4i
printf "sqrt($d) = %s\n", sqrt($d);

sqrt(3+4i) = 2+i

The original Math::Complex module distributed with 5.003 did not overload as many functions and operators as the 5.004 version does. Also, the Math::Trig module (new as of 5.004) uses the Math::Complex module internally because some functions can break out from the real axis into the complex plane - for example, the inverse sine of 2.

See Also

The documentation for the standard Math::Complex module (also in Chapter 7 of Programming Perl)


Previous: 2.14. Multiplying MatricesPerl CookbookNext: 2.16. Converting Between Octal and Hexadecimal
2.14. Multiplying MatricesBook Index2.16. Converting Between Octal and Hexadecimal