Skip to content

Complex numbers operations: sum, mul, abs #5054

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions maths/complex/abs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
from math import sqrt

from complex import Complex


def complex_abs(c: Complex) -> float:
"""
Computes the absolute value of a complex number.
The result is a non-negative real number, that represents the lenght
of the vector (real_part, imaginary_part) in R².
>>> c = Complex(-3, 4)
>>> complex_abs(c)
5.0
"""
return sqrt(c.real_part ** 2 + c.imaginary_part ** 2)
23 changes: 23 additions & 0 deletions maths/complex/complex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""
Complex number implementation.

Definition:
A complex number is an ordered pair of real numbers (a, b). The first
component, a, is called the real part; the second component, b, is called
the imaginary part.
"""


class Complex:
def __init__(self, real_part: float, imaginary_part: float):
"""
Both a and b are real numbers (float in Python).
"""
self.real_part = real_part
self.imaginary_part = imaginary_part

def __repr__(self) -> str:
"""
Represent the complex number as a 2-tuple.
"""
return (self.real_part, self.imaginary_part)
16 changes: 16 additions & 0 deletions maths/complex/mul.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
from complex import Complex


def complex_mul(a: Complex, b: Complex) -> Complex:
"""
Multiplicate two complex numbers and return the result.
>>> a = Complex(0, 1)
>>> b = Complex(0, 1)
>>> c = complex_mul(a, b)
>>> c.__repr__()
(-1, 0)
"""
return Complex(
a.real_part * b.real_part - a.imaginary_part * b.imaginary_part,
a.real_part * b.imaginary_part + b.real_part * a.imaginary_part,
)
19 changes: 19 additions & 0 deletions maths/complex/sum.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from complex import Complex


def complex_sum(a: Complex, b: Complex) -> Complex:
"""
Add two complex numbers and return the result.
>>> a = Complex(1, 2)
>>> b = Complex(0, -1)
>>> c = complex_sum(a, b)
>>> c.__repr__()
(1, 1)
"""
return Complex(a.real_part + b.real_part, a.imaginary_part + b.imaginary_part)


if __name__ == "__main__":
import doctest

doctest.testmod()