Деление комплексных чисел в классе Python 3 - PullRequest
1 голос
/ 25 мая 2019

У меня проблемы с созданием метода __div__ в классе Python для комплексных чисел, которые должны делить два комплексных числа.

Вот мой код:

class Complex(object):
        def __init__(self, real = 0, imag = 0):
            self.real = real
            self.imag = imag

        def __str__(self):
            if self.imag > 0:
                return str(self.real) + "+" + str(self.imag) + "i"
            elif self.imag < 0:
                return str(self.real) + str(self.imag) + "i"

        def __div__(self, other):
            x = self.real * other.real + self.imag * other.imag
            y = self.imag * other.real - self.real * other.imag
            z = other.real**2 + other.imag**2
            real = x / z
            imag = y / z
            return Complex(real, imag)

no = Complex(2,-8)
no2 = Complex(3,7)
print(no/no2)

К сожалению, мой подход не работает. Есть предложения?

Ответы [ 3 ]

3 голосов
/ 26 мая 2019

__div__ больше не существует в Python 3. Его заменили на __truediv__ для / и __floordiv__ для //

Посмотрите на https://docs.python.org/3/reference/datamodel.html

2 голосов
/ 26 мая 2019

Это __truediv__, а не __div__.__div__ было названием старого Python 2 «floordiv для целочисленного, truediv для нецелочисленного» деления.

Пока вы исправляете вещи, вам, вероятно, следует добавить else регистр в __str__.

1 голос
/ 26 мая 2019

вам нужно создать метод __div__(self, other), где вы делите no, а также новый метод __opposite__(self), чтобы изменить знак при умножении, также вызывая метод, как делить, т.е. no / no1 не является божественным методом

с использованием решения @johnO, обнуляя __truediv__, поэтому OP может использовать no/no2 для разделения двух комплексных чисел.

см. Код ниже

class Complex (объект): def init (self, real = 0, imag = 0): self.real = real self.imag = imag

    def __str__(self):
        if self.imag > 0:
            return str(self.real) + "+" + str(self.imag) + "i"
        elif self.imag < 0:
            return str(self.real) + str(self.imag) + "i"
    def __opposite__(self):
        self.real =self.real
        self.imag = self. imag if self.imag<0 else self.imag * -1


    def __truediv__(self, other):
        other.__opposite__()



        x = self.real * other.real - self.imag * other.imag
        y = self.imag * other.real + self.real * other.imag
        z = other.real**2 + other.imag**2
        self.new_real = x / z
        self.new_imag = y / z
        if self.new_imag>0:
            result = "{} + {}i".format(self.new_real, self.new_imag)
        else:
            result = "{} {}i".format(self.new_real, self.new_imag)
        return result

no = Complex(4,5)
no2 = Complex(2,6)
print(no/no2)

output

0.24 + 0.68i
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...