Python: Making a class to use complex numbers

2024/10/5 15:13:41

I am currently trying to write a program that deals with complex numbers. I have to use classes and methods. I am trying to be able to add, subtract, multiply etc., complex numbers, as well as compare them to one another. I think I have gotten a good start but have some issues.

I have started each method, and I think I just need to fill in the gaps. In the method, I used self.x as a placeholder. I'm not really sure what goes there. First off, the program needs to create it's own complex numbers. I'm new to making methods and functions and I'm not sure if I used (self) in the correct places.

I'm pretty sure I have some syntax issues, i.e. It keeps saying that the variable "i" is not defined, when I clearly have it defined in multiple places.

Once all this is sorted out, I need to create a test function that actually uses the code.

Any help would be appreciated. Thanks!

My code so far:

import math
i = math.sqrt(-1) class Complex(object):def __init__(Complex, a, b):'''Creates Complex Number'''a = 0b = 0return(Complex, a, b) def __str__(Complex, a, b):'''Returns complex number as a string'''a = 0b = 0return str(a, b) def __add__(self):'''Adds complex numbers'''i = math.sqrt(-1) self.x = (a + bi) + (c + di) = (a + c) + (b + d)idef __sub__(self):'''Subtracts complex numbers'''self.x = (a + bi) - (c + di) = (a - c) + (b - d)idef __mul__(self):'''Multiplies complex numbers'''self.x =  (a + bi) * (c + di) = (ac - bd) + (bc + ad)idef __div__(self):'''Divides complex numbers'''self.x =  (a + bi) / (c + di) = (ac + bd)/(c**2 + d**2) + (bc - ad)i/(c**2 + d**2)def __abs__(self):'''Determines absolute value of complex numbers'''self.x = math.sqrt(a**2 + b**2)
Answer

Here's a simple implementation of just a subset of what you're trying to do:

import mathclass Complex(object):def __init__(self, a, b):'''Creates Complex Number'''self.a = aself.b = bdef __str__(self):'''Returns complex number as a string'''return '(%s, %s)' % (self.a, self.b) def __add__(self, rhs):'''Adds complex numbers'''return Complex(self.a + rhs.a, self.b + rhs.b)i = Complex(0, 1)

To break down the __add__ method a bit more for exposition:

    def __add__(self, rhs):'''Adds complex numbers'''new_a = self.a + rhs.anew_b = self.b + rhs.breturn Complex(new_a, new_b)

Or, relating it more directly to your original:

    def __add__(self, rhs):'''Adds complex numbers'''a = self.ab = self.bc = rhs.ad = rhs.bnew_real_part = a + cnew_imag_part = b + dreturn Complex(new_real_part, new_imag_part)

This might all be simpler if you avoided calling your member variables a and b, which are pretty generic and meaningless, and can cause confusion when you're dealing with algorithms where the real and imaginary parts of an object might be referred to as a and b, or c and d, or various other things.

Can you figure out the rest from here?

Note that the only place you should need math is inside __abs__.

For a rundown of some of the things you got wrong in the original:

  • You defined your global variable i in terms of math.sqrt(-1), which raises an exception. And the only way this could possibly work would be to return a native complex number—since the whole point of what you're trying to do is create your own complex class instead of using the native support, this would be pointless. Instead, you want to define i as an instance of your class.
  • All instance methods—including __init__—should take self as the first parameter.
  • The only way to access instance variables—including setting them in __init__—is via the self parameter. a = 0 just creates a new local variable that goes away as soon as the function is over; self.a = 0 modifies the a member of the object.
  • The __str__ method doesn't take any extra parameters.
  • The __add__ method shouldn't be changing the object in-place, but returning a new one. If you want to change the object in-place, that's __iadd__. (It's pretty common to define __add__ in terms of __iadd__, as you might guess.) And the same is true for the next three methods.
  • The __add__ method has to take another parameter to operate on. Otherwise, what are you adding self to? And again, ditto for the next few methods.
  • You don't have an x member, so why are you setting one in __add__? (Of course this is legal, and will create a new one, but you're never going to use it anywhere.)
  • Your algorithms seem to be trying to create a native complex value. If you want to get a Complex whose real part is the sum of the real parts of self and rhs and whose imaginary part is the sum of the imaginary parts, you have to construct a Complex out of those two sums. (You don't have any way to construct a Complex out of a single combined value.)
  • What did you expect self.x = … = … to do? For example, are you really trying to assign the value of (a + c) + (b + d)i to the expression (a + bi) + (c + di)?
  • Juxtaposition doesn't mean multiplication in Python, or most other programming languages. So bi is an entirely separate variable, not b times i, and (b + d)i is a syntax error.
https://en.xdnf.cn/q/120183.html

Related Q&A

Return does not return anything in Spyder. It works fine with other IDE

I just moved to spyder for Python and the return function doesnt seem to work: def test():return 2 test()The IPython console is empty. If I use print instead of return it works fine. Any idea? I use p…

Error in goto module [Python]

Ok, let me start by saying I know that it is bad that I am using the goto module and I shouldnt be and blah blah blah. However, for this specific purpose I need it. Let me also say that I am new to Pyt…

How to scrape all product review from lazada in python

i currently working on web scraping of data from the lazada site using selenium in python: https://www.lazada.sg/products/loreal-paris-uv-perfect-even-complexion-sunscreen-spf50pa-30ml-i214861100-s325…

How to compare 2 successive row values in a resultset object using python

I have a table issue_logs:id | issue_id | from_status | to_status | up_date | remarks ----+----------+-------------+-----------+----------------------------------+----------…

Getting all possible combination for [1,0] with length 3 [0,0,0] to [1,1,1]

from itertools import combinationsdef n_length_combo(arr, n):# using set to deal# with duplicates return list(combinations(arr, n))# Driver Function if __name__ == "__main__":arr = 01n = 3pri…

Compare values under multiple conditions of one column in Python

I have the following data:data = {"index": [1, 2, 3, 4, 5],"name": ["A", "A", "B", "B", "B"],"type": [s1, s2, s1, s2, s3]…

Python: Tkinter :Dynamically Create Label

I am trying to create Label Dynamically , I am getting invalid Syntax. Can you please help me what i am missing or any alternativecrsr = cnxn.execute(query)row_num=2column_num=0Variable_Number=1for row…

TypeError: str object is not callable when trying to click datepicker

The relevant HTML<div id="datepickerbox" class="ym-gbox-left"><div class="datepick_label"><div id="datepicker" class="hasDatepicker">…

Stanford parser with NLTK produces empty output

I am trying to use the Stanford parser in a small application written in Python with the NLTK interface. I tried the code given below.Everything seems to work right, no errors, Java is launched but I s…

How do you return a list of the matched item in string with regex? [duplicate]

This question already has answers here:Regular expression to match a dot [duplicate](8 answers)Closed 3 years ago.I made this simple functions that searches for emails in the source code of a page , th…