Perl & Python: Complex Numbers

Advertise Here

, ,

Python

Python supports complex numbers. Append a j to a number and it represents the imaginary number. For example, 3j means 3*ⅈ. A complete complex number (3,4) can be written as complex(3,4) or 3+4j.

Arithmetic operations can be applied in the usual way. To get the real part, imaginary part, or length, do it like this:

# Python
a=complex(3,4)
print a.real
print a.imag
print abs(a)
print complex(3,4)+5+6j

http://docs.python.org/lib/typesnumeric.html

Perl

Perl doesn't support complex numbers. But there are packages for it. One of them is “Math::Complex”.

Here's a excerpt from its documentation:

SYNOPSIS
            use Math::Complex;

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

DESCRIPTION
    This package lets you create and manipulate complex numbers. By default,
    *Perl* limits itself to real numbers, but an extra "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

    …

From this, we observe the general Perl programer's understanding of mathematics, and also this package's author's understanding of it. And, as well as the fanaticality and maturity from the writing style.

perldoc Math::Complex

blog comments powered by Disqus