Python mintapélda - Belépés

Komplex számok (a Python nyelv biztosítja a komplex számok kezelését, nincs szükség saját komplex osztály létrehozására)

# -*- coding: utf-8 -*-
"""
.. module:: complex
:platform: Linux, Windows

.. moduleauthor: Zoltan Siki

"""

class Complex(object):
""" class to handle complex numbers
"""
def __init__(self, re=0, im=0):
""" Initialize complex number
:param re: real part
:param im: imaginary part
"""
self.re = re
self.im = im

def abs(self):
""" calculate length of vector (absolute value)
:returns: absolute value
"""
return (self.re**2 + self.im**2)**0.5

def conjugate(self):
""" Conjugate of the complex number
"""
return Complex(self.re, -self.im)

def __str__(self):
""" String representation of the complex number
:returns: complex number as string (e.g. 5 + 3i)
"""
return "%.3f + %.3fi" % (self.re, self.im)

def __add__(self, c):
""" Add two complex number
:param c: complex number to add
:returns: the sum of the two complex number
"""
return Complex(self.re + c.re, self.im + c.im)

Utolsó módosítás: 2017. március 9., csütörtök, 15:11