Python Forum
complex numbers - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Data Science (https://python-forum.io/forum-44.html)
+--- Thread: complex numbers (/thread-18149.html)



complex numbers - mcgrim - May-07-2019

I am trying to come up with methods for addition and subtraction of complex numbers,

so that the print statement should generate something like
1+2i
1-2i

if I want to use an interval (1,2).

This is my code:

class comp_num(object):
    def __init__(self, real_1, real_2):
        self.real_1=real_1
        self.real_2=real_2
    
    def __add__(self):
        a,b=self.real_1, self.real_2
        return complex(a,b)
    
    def __sub__(self):
        a,b=self.real_1, self.real_2
        return complex(a,b).conjugate()
    
    def __repr__(self):
        return '[{},{}]'.format(self.real_1. self.real_2)
    

print(comp_num(1,2))
and this is the error I get:

Error:
runfile('C:/Users/Desktop/python ode/ex8.py', wdir='C:/Users/Desktop/python ode') Traceback (most recent call last): File "<ipython-input-807-415135f62ea4>", line 1, in <module> runfile('C:/Users/Desktop/python ode/ex8.py', wdir='C:/Users/Desktop/python ode') File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 668, in runfile execfile(filename, namespace) File "C:\Users\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 108, in execfile exec(compile(f.read(), filename, 'exec'), namespace) File "C:/Users/Desktop/python ode/ex8.py", line 28, in <module> print(comp_num(1,2)) File "C:/Users/Desktop/python ode/ex8.py", line 22, in __repr__ return '[{},{}]'.format(self.real_1. self.real_2) AttributeError: 'int' object has no attribute 'self'



RE: complex numbers - buran - May-07-2019

line 15, format() method - you have dot instead of comma between self.real_1 and self.real_2


RE: complex numbers - mcgrim - May-07-2019

Thank you.

It runs now but only prints [1,2].

How do I actually make sure that 1+2i and 1-2i are printed ?


RE: complex numbers - buran - May-07-2019

(May-07-2019, 12:36 PM)mcgrim Wrote: How do I actually make sure that 1+2i and 1-2i are printed ?


change your __repr__ function accordingly (i.e. to output what you want)
I think there is some confusion as it's not clear what you want to achieve
>>> complex(1, 2)
(1+2j)
>>> complex(1, 2).conjugate()
(1-2j)
>>>