Mathematics with Python and Ruby/Complex numbers in Ruby



As real numbers can be strictly ordered while complex numbers can't be, an object oriented language such as Ruby doesn't really consider the complex numbers as numbers. Yet Ruby has an object to handle these numbers, and it is called Complex.

Example
For example, to create the complex number 4+3i it suffices to write

This needs two numbers which can be fractions or integers. In this last case, the complex number is a gaussian integer. This information could be useful at a dinner, who knows?

Basic operations
Addition, subtraction, multiplication and division are still denoted by +, -, * and /:

These examples show that the sum, the difference and the product of two gaussian integers are gaussian too, but their quotient is not necessarily gaussian. The example with the subtraction shows that even when the result of an operation is real, Ruby does consider it as complex anyway.

Exponentiation
To raise a complex to a power, the double asterisk is still used:

Here $$i^2=0i-1$$ and not really -1! Also, $$i^i$$ is a real number! By the way an exponent need not be a real number.

But with 0.5 as an exponent one can compute the square root of a complex number. But any complex number (except zero) has two square roots. How does Ruby choose between them? For example the square roots of 7+24i are 4+3i and -4-3i. Ruby chooses the first one. Other examples:

If -1 is seen as a real number, it has no square root at all, whereas considered as a complex number, it has two square roots, the one which is nearest to i is displayed (but it is not exactly equal to i because of roundup errors)

Example
The two (real) numbers which are used to create a complex number are its real part and imaginary part. They can be obtained with real and imag:

This example shows an othe property, the conjugate of a complex number, which, contrary to the other ones, is a complex number too.

Geometrical properties
The main properties of a complex number which are useful to geometry are its modulus and argument:

The last property, polar, gives at the same time the modulus and the argument, which allows one to solve the problem from the last chapter:

=Functions=

with require 'cmath'  one can access to functions on complex numbers.

Exponential
This example shows how legitimate it is to write $$e^{-\frac{\pi}{3}i}$$ for $$\frac{1}{2}+i\frac{\sqrt{3}}{2}$$.

The hyperbolic functions are also available for the complex numbers:

Logarithms
The inverses of the preceding function can also be applied to complex numbers:

Direct
Every complex number has a cosine, a sine and a tangent:

Inverse
It is even possible to apply atan2 to a pair of complex numbers:

This complex version of the atan2 function is a good example of a complex surface: atan2(-1,-1) = 5&pi;/4, whereas atan2(1,1) = atan(1) = &pi;/4: