坚持上课活动。寻找快速课程。复数

时间:2017-09-13 03:51:54

标签: python-3.x function class numbers complex-numbers

我在抓住课程的目的时遇到了麻烦。我无法正确完成这项任务,但我需要知道这项考试。我目前收到的输出是

(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)

1 个答案:

答案 0 :(得分:0)

您需要按照提供的add方法构建您正在编写的方法。您需要为returnself.real分配新值,而不是self.imag某些值。乘法,除法和取幂的计算比添加要复杂得多,因此您在计算时可能需要一些临时变量来保存值。

而不是为你完成整件事,我只做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乘以其复共轭所得到的实际值。新值的两个表达式都可以使用该中间值。