複素数計算

30分プログラム、その215。複素数クラスを作ってみる。
複素数の計算が目的なのではなくて、+や-などの演算子オーバーロードしてみたかっただけ。Pythonにcomplex型があることは知っているけど、他にいい題材が思いつかなかったので。有理数は昔(id:mzp:20070925:ratio)やったし。

あと、Pythonでprivateなメソッド/変数は先頭に__をつけることで実現するらしいです。ネームマングリングといって、self.__Xがself__ClassName__Xに変換されて、外部から誤ってアクセスされるのを防がれるそうです。

使い方

>>> c1 = Complex(1,2)
>>> c2 = Complex(3,4)

>>> c1
1.000000+2.000000i

>>> c2
3.000000+4.000000i

>>> c1+c2
4.000000+6.000000i

>>> c1*c2
-5.000000+10.000000i

ソースコード

#! /usr/bin/python
# -*- mode:python; coding:utf-8 -*-
#
# complex.py -
#
# Copyright(C) 2008 by mzp
# Author: MIZUNO Hiroki / mzpppp at gmail dot com
# http://howdyworld.org
#
# Timestamp: 2008/01/05 20:55:20
#
# This program is free software; you can redistribute it and/or
# modify it under MIT Lincence.
#
import math
class Complex:
    def __init__(self,real,image):
        self.real = real
        self.image = image

    def __repr__(self):
        return '%f+%fi' % (self.real,self.image)

    def __add__(self,other):
        return Complex(self.real  + other.real,
                       self.image + other.image)

    def __sub__(self,other):
        return self.__add__(-other)

    def __mul__(self,other):
        return other.__mul(self.real) + other.__mul(self.image).conj().__revert()

    def __div__(self,other):
        denom = float((other * other.conj()).real)
        return (self * other.conj()).__div(denom)

    def __neg__(self):
        return Complex(-self.real,-self.image)

    def __abs__(self):
        return math.sqrt(self.real*self.real+self.image*self.image)

    def conj(self):
        return Complex(self.real,-self.image)

    # private
    def __mul(self,c):
        return Complex(c*self.real,c*self.image)

    def __div(self,c):
        return Complex(self.real/c,self.image/c)

    def __revert(self):
        return Complex(self.image,self.real)

if __name__ == '__main__':
    c1 = Complex(1,2)
    c2 = Complex(3,4)
    print c1
    print c2
    print c1+c2
    print c1-c2
    print abs(c2)
    print c2.conj()
    print c1*c2
    print c1/c2