Section 5.12. Using mathn


5.11. Working with Complex Numbers

The standard library complex enables us to handle imaginary and complex numbers in Ruby. Much of it is self-explanatory.

Complex values can be created with this slightly unusual notation:

z = Complex(3,5)     # 3+5i


What is unusual about this is that we have a method name that is the same as the class name. In this case, the presence of the parentheses indicates a method call rather than a reference to a constant. In general, method names do not look like constants, and I don't recommend the practice of capitalizing method names except in special cases like this. (Note that there are also methods called Integer and Float; in general, the capitalized method names are for data conversion or something similar.)

The im method converts a number to its imaginary counterpart (effectively multiplying it by i). So we can represent imaginary and complex numbers with a more convenient notation:

a = 3.im       # 3i b = 5 - 2.im   # 5-2i


If we're more concerned with polar coordinates, we can also call the polar class method:

z = Complex.polar(5,Math::PI/2.0)   # radius, angle


The Complex class also gives us the constant I, which of course represents i, the square root of negative one:

z1 = Complex(3,5) z2 = 3 + 5*Complex::I    # z2 == z1


When complex is loaded, certain common math functions have their behavior changed. Trig functions such as sin, sinh, tan, and tanh (along with others such as exp and log) accept complex arguments in addition to their normal behavior. In some cases, such as sqrt, they are "smart" enough to return complex results also.

x = Math.sqrt(Complex(3,5))  # roughly: Complex(2.1013, 1.1897) y = Math.sqrt(-1)            # Complex(0,1)


For more information, refer to any comprehensive source of documentation such as the ruby-doc.org site.




The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net