以下は実装した複素数クラスのコードです
import math class Cpx: def __init__(self, re=0., im=0.): self._re = float(re) self._im = float(im) @property #ゲッタ def re(self): return self._re @re.setter #セッタ def re(self, value): self._re = value @property #ゲッタ def im (self): return self._im @im.setter #セッタ def im(self, value): self._im = value def __repr__(self): return self.__str__() def __str__(self): str_ = '' if self.re == 0 else str(self._re) str_ += '' if self._im < 0 else '+' str_ += str(self._im) + 'i' return str_ def __eq__(self,other): return self.re == other.re and self.im == other.im def __sum__(self, other): return Cpx(self._re + other.re, self._im + other.im) def __sub__(self,other): return Cpx(self._re - other.re, self._im - other.im) def __mul__(self,other): return Cpx(self._re * other.re - self._im * other.im, self._re * other.\ im + other.re * self._im) def __truediv__(self,other): a = other.re**2 + other.im**2 return self * other.conj() / a
実行したいことは二つの複素数の四則演算です
u = Cpx(1.23,-6.2) v = Cpx(4,5) print(str(u)) print(str(v)) print(u*v) print(u-v) print(u+v) print(u/v)
足し算と割り算だけうまくいきません
以下は足し算のエラーコードです
TypeError: unsupported operand type(s) for +: 'Cpx' and 'Cpx'
割り算のエラーコードです
File "Cpx.py", line 82, in <module> print(u/v) File "Cpx.py", line 73, in __truediv__ return self * other.conj() / a File "Cpx.py", line 72, in __truediv__ a = other.re**2 + other.im**2 AttributeError: 'float' object has no attribute 're'
エラーコードの説明の言いたいことはなんとなくわかるのですが、どこを修正すれば良いかわかりません。
まだクラスについても完璧に理解しているとは言えないです。
このプログラムで問題なく演算ができるために、どこを修正すれば良いか教えていただきたいです。
公式ドキュメントのclass complex([real[, imag]])を使えば、新たにクラスを定義する必要はありません。
https://docs.python.org/ja/3/library/functions.html#complex
回答2件
あなたの回答
tips
プレビュー