This module implements cplx class (complex numbers) regardless to the
built-in class.
The main goal of this module is to propose some improvement to complex
numbers in python and deal with them from a mathematical approach.
Also cplx class doesn't support the built-in class intentionally, as the
idea was to give an alternative to it.
With the hope I managed to succeed, here is the module :
# Module for complex numbers (doesn't support the built-in complex class)
# Originally contributed by TBER Abdelmalek
import re, math
from fractions import Fraction as Q
if __name__ == '__main__' :
import os, Complex
help(Complex)
os.system("pause")
_supported = (int, float, Q, str, tuple, list) # Supported types for
instanciation and operations for cplx class
class cplx :
"""This class implements complex numbers at the form of 'a+bi'
with a : the real part, and b : the imaginary part.
a and b are real numbers : [integers, floating numbers, or
fractions (from Fraction class of fractions module), refered here by
Q].
Construction of complex numbers can be from two major ways :
- cplx([real part[, imaginary part]]) :
Two real numbers arguments given and both optionals, so
that cplx() = 0
For fractions use Fraction class : cplx(Q(n,d),Q(n',d'))
for details about Fraction, see help(Fraction).
-cplx('valid form of a complex number in a STRING'):
The advantage of this way is the ease of fractions use
with '/'.
Examples : cplx('2i-1/4')
cplx('6 - 1/5 * i') # spaces don't bother at
all
cplx('7i')
"""
global _supported
def __init__(self, a=0, b=None):
if isinstance(a, str) and b is None: # construction from string
if a == '' :
self.re = 0
self.im = 0
elif cplx.verify(a):
part_one = ''
part_two = ''
switch = False
first = True
for c in a :
if c in ('+', '-') and not first :
switch = True
part_two += c
elif not switch :
if c.isalnum() or c in ('+',
'-', '/') : part_one += c
elif c in (',', '.') : part_one
+= '.'
else :
if c.isalnum() or c == '/' :
part_two += c
elif c in (',', '.') : part_two
+= '.'
first = False
if 'i' in part_two :
part_two = part_two[:len(part_two)-1]
if '.' in part_one : self.re =
float(part_one)
elif '/' in part_one : self.re =
Q(part_one)
else : self.re = int(part_one)
if '.' in part_two : self.im =
float(part_two)
elif '/' in part_two : self.im =
Q(part_two)
elif part_two == '+' : self.im = 1
elif part_two == '-' : self.im = -1
else : self.im = int(part_two)
elif 'i' in part_one :
part_one = part_one[:len(part_one)-1]
if part_two == '' : self.re = 0
elif '.' in part_two : self.re =
float(part_two)
elif '/' in part_two : self.re =
Q(part_two)
else : self.re = int(part_two)
if '.' in part_one : self.im =
float(part_one)
elif '/' in part_one : self.im =
Q(part_one)