Python Forum
help with assignment 3
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
help with assignment 3
#1
Hi,
I'm working with complex numbers (multiply,substract, absolute value)

input:
class Complex(object):
    def __init__(self, r, i):
        self.real = r
        self.imag = i

my_number1 = Complex(9,34)
my_number2 = Complex(2,11)

print(my_number1.real)
print(my_number1.imag)
print(my_number2.real)
print(my_number2.imag)
print(my_number1.sub(my_number2).real)
print(my_number1.sub(my_number2).imag)
output:
9
34
2
11
Traceback (most recent call last):
  File "hw.py", line 35, in <module>
    print(my_number1.sub(my_number2).real)
AttributeError: 'Complex' object has no attribute 'sub'
What am I doing wrong?

Thanks in advance for help!
Reply
#2
sub should be a method but is not defined.
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#3
What's wrong here?
I need to find absolute values of random complex numbers.
input:
class Complex(object):
    def __init__(self, r, i):
        self.real = r
        self.imag = i
        
    def abs(self, other): 
            return sqrt(self.real**2 + self.imag**2)

my_number1 = Complex(9,34)
my_number2 = Complex(2,11)

print(my_number1.real)
print(my_number1.imag)
print(my_number2.real)
print(my_number2.imag)
print(my_number1.abs(my_number2).real)
print(my_number1.abs(my_number2).imag)
output:

9
34
2
11
Traceback (most recent call last):
  File "hw.py", line 76, in <module>
    print(my_number1.abs(my_number2).real)
  File "hw.py", line 67, in abs
    return sqrt(self.real**2 + self.imag**2)
NameError: name 'sqrt' is not defined
Reply
#4
You have to import the math module.

>>> import math
>>> math.sqrt(40)
6.324555320336759
>>> 
"As they say in Mexico 'dosvidaniya'. That makes two vidaniyas."
https://freedns.afraid.org
Reply
#5
You have to import this function:
from math import sqrt
Otherwise the name is not defined.
If you want to modify the complex object, just use the type complex as subclass:

class Complex(complex):
    def __float__(self):
        return abs(self)


float(complex(1,2)) # Error, method does not exist
float(Complex(1,2)) # Own implementation
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#6
Thanks!
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020