Learn Object Oriented Programming by re-implementing Python’s Complex class: Part-3
The previous one covered usage of built-in complex class. It’s time to write our own code to handle complex numbers. This story focuses on creating and handling complex numbers using functions only. So the OO(Object Oriented Treatment) will come in the next part.
Before we get our hands dirty, lets see what all we will do.
- Represent complex numbers using a tuple.
- Write method to find conjugate and negate: Unary Operations
- Add and Subtract methods: Binary Operations
- Multiplication and Division
Complex number in a Tuple
We are going to put the real and imaginary part of a complex number into a tuple. So or representation for 1 + 2i
will be (1,2)
. Element at index 0 will be real part and one at index 1 will be imaginary part.
For numbers having only real or imaginary part will be represented like this:
10 => (10, 0)
20i => (0,20)
-2i => (0,-2)
In Python we can create like this
To print these in a proper format lets define a function print_complex
.
For negative imaginary part it looks weird. Update code looks like this
Looks better now !
Conjugate and Negative
Two simple functions will do our job.
Addition and Subtraction
That’s also quite easy to do. So just functions again.
Subtraction can also be implemented as addition of the negative. For now we have written it simple. In next part where we do the Object Oriented treatment, we will use that way.
Multiplication and Division
These operations are more complex than the previous ones. Multiplication is much more simpler to do than Division. See below code
For division we need help of previously defined function.
That’s it for this story. Next one covers Object Oriented treatment along with magic methods(operator overloading in python).
Prev: Complex Numbers 2: Python’s Complex class