被困在班级活动中。寻找一个快速教训。复数
问题描述:
我有麻烦抓类的目的。我无法完成这项任务,但我需要知道这个考试。我目前接收的输出是被困在班级活动中。寻找一个快速教训。复数
(7,1)
(7,1)
(7,1)
这显然是不正确的。如果有人能够解释这个问题的思维过程,我将非常感激。我无法弄清楚。 (编码方面的新内容,老师还没有教过这些材料,但已将这个问题分配给作业)
函数名称和变量不能更改。再次感谢你。
# Goal: complete the three functions multiply, divide and power below
#
# - self is Complex, which is a complex number whose Re is self.real and
# Im is self.imag
# - multiply(c) replaces self by self times c, where c is Complex
# - divide(c) is to replace self by self divided by c
# - power(n) is to replace self by self to the power n
#
# See https://en.wikipedia.org/wiki/Complex_number
#
# Submission:
# file name: EX9_8.py
# Do not change the function and class names and parameters
# Upload to Vocareum by the due date
#
#
import math
class Complex:
def __init__ (self, r, i):
self.real = r
self.imag = i
# Copy the three functions from Activity 1 of vLec9_8
def magnitude(self):
return math.sqrt(self.real**2 + self.imag**2)
def conjugate(self):
self.imag *= -1
def add(self, c):
if not isinstance(c, Complex):
return "Type Mismatch Error"
self.real += c.real
self.imag += c.imag
#The Following Functions are the assignment I am working on. The above functions were already given.
def multiply(self, c):
new = (self.real + self.imag) * (c.real + c.imag)
return new
#Procedural method: multiply self by c to change self where c is Complex
def divide(self, c):
new2 = ((self.real + self.imag)*(c.real - c.imag))/((c.real + c.imag)*(c.real - c.imag))
return new2
#Procedural method: divide self by c to change self where c is Complex
def power(self, n):
new3 = math.cos(n.real) + ((n.imag)*(math.sin(n.real)))
return new3
# Procedural method: take self to the power n to change self,
# where n is a positive integer
# test code
c1 = Complex(3,2)
c2 = Complex(4,-1)
c1.add(c2)
print((c1.real, c1.imag))
c1.power(4)
print((c1.real, c1.imag))
c1.divide(c2)
print((c1.real, c1.imag))
# should prints
#(7, 1)
#(2108, 1344)
#(416.94117647058823, 440.2352941176471)
答
您需要构建您正在编写的方法,如提供的方法add
。您需要为self.real
和self.imag
分配新值,而不是return
。乘法,除法和求幂的计算比加法要复杂一点,所以在计算时可能需要一些临时变量来保存值。
,而不是为你做这件事,我只是做multiply
,这将给你一个框架,你可以使用别人:
def multiply(self, c):
if not isinstance(c, Complex): # type checking code copied from add()
return "Type Mismatch Error" # raising an exception would probably be better
new_real = self.real * c.real - self.imag * c.imag
new_imag = self.real * c.imag + c.real * self.imag
self.real = new_real
self.imag = new_imag
为师,您可能需要另一个临时变量保存通过复数共轭乘以c
得到的实际值。新值的两个表达式都可以使用该中间值。
嗯,实际上,除了'conjugate'和'add',你的类方法都没有修改'self.real'和'self.imag',所以(7,1) - 是正确的输出 –
“... (7,1),(7,1),(7,1)..这显然是不正确的“,正确的输出是什么? – davedwards