Wikibooksβ

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.

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

a=Complex(2,3)b=Complex(4,3)puts(a+b)puts(a-b)puts(a*b)puts(a/b)

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.

Here i2=0i−1{\displaystyle i^{2}=0i-1} and not really -1! Also, ii{\displaystyle 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:

puts((-1)**0.5)puts(Complex(-1,0)**0.5)

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)