Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1
>>> test2 = Fraction(4, 3)
>>> result = test1 * test2
>>> print(result)
4/9
>>>

Python will also work out common denominator problems with your fractions, like this:


>>> test1 = Fraction(1,3)
>>> test2 = Fraction(1,2)
>>> result = test1 + test2
>>> print(result)
5/6
>>>

Now you can perform calculations with fractions just as easily as with decimal numbers. That can
make life a lot easier if you’re working in an environment that uses fractions!


Using Complex Number Math


For the scientific and engineering communities, Python also supports complex numbers, as well as
complex number calculations. A complex number is represented by a combination of a real number
and an imaginary number.


By the Way: Imaginary Numbers
By definition, an imaginary number is the square root of –1, which theoretically
doesn’t exist, thus the term imaginary.

A complex number is represented by the real number, a plus sign, and the complex number, followed
by a j. For example, in the complex number 1 + 2j, 1 is the real component, and 2 is the imaginary
component.


Trying to work with calculations that use complex numbers is, well, complex! The combination of the
real and imaginary parts of the complex number causes the calculations to behave somewhat
differently from the math operations you’re probably use to seeing. This section walks through how to
handle complex numbers in your Python scripts.


Creating Complex Numbers


You define complex numbers by using the complex() function, which is built into the core Python
language. As you can see in this example, to create the complex number, you just specify the real
component value as the first parameter and then the imaginary component value as the second
parameter:


>>> test = complex(1, 3)
>>> print(test)
(1+3j)
>>>

When you need to display the complex number value, Python displays it using the j format, making it
easier to view.


Complex Number Operations

Free download pdf