From 889cf99695403cc8af424eab38a3e78c971a2ec2 Mon Sep 17 00:00:00 2001 From: blueloveTH Date: Sat, 30 Dec 2023 20:58:52 +0800 Subject: [PATCH] ... --- include/typings/c.pyi | 2 +- python/cmath.py | 10 ++++++++-- tests/10_cmath.py | 20 +++++++++++--------- 3 files changed, 20 insertions(+), 12 deletions(-) diff --git a/include/typings/c.pyi b/include/typings/c.pyi index 06b1345f..41628465 100644 --- a/include/typings/c.pyi +++ b/include/typings/c.pyi @@ -1,4 +1,4 @@ -from typing import overload, Generic, TypeVar +from typing import Generic, TypeVar def malloc(size: int) -> 'void_p': ... def free(ptr: 'void_p') -> None: ... diff --git a/python/cmath.py b/python/cmath.py index 60ec66c4..bb2dec50 100644 --- a/python/cmath.py +++ b/python/cmath.py @@ -21,9 +21,9 @@ class complex: def __eq__(self, other): if type(other) is complex: - return math.isclose(self.real, other.real) and math.isclose(self.imag, other.imag) + return self.real == other.real and self.imag == other.imag if type(other) in (int, float): - return math.isclose(self.real, other) and self.imag == 0 + return self.real == other and self.imag == 0 return NotImplemented def __add__(self, other): @@ -69,6 +69,9 @@ class complex: def __abs__(self) -> float: return math.sqrt(self.real ** 2 + self.imag ** 2) + + def __hash__(self): + return hash((self.real, self.imag)) # Conversions to and from polar coordinates @@ -147,6 +150,9 @@ def isinf(z: complex): def isnan(z: complex): return math.isnan(z.real) or math.isnan(z.imag) +def isclose(a: complex, b: complex): + return math.isclose(a.real, b.real) and math.isclose(a.imag, b.imag) + # Constants pi = math.pi diff --git a/tests/10_cmath.py b/tests/10_cmath.py index eb443bc0..e4cd077c 100644 --- a/tests/10_cmath.py +++ b/tests/10_cmath.py @@ -1,20 +1,22 @@ +from cmath import isclose, sqrt + assert 1+2j == complex(1, 2) == 2j+1 -assert 1+2j + 3+4j == 4+6j +assert isclose(1+2j + 3+4j, 4+6j) -assert 1+2j - 3+4j == -2+6j +assert isclose(1+2j - 3+4j, -2+6j) assert (1+2j).real == 1 assert (1+2j).imag == 2 -assert (1+2j)*(3+4j) == -5+10j -assert (1+2j)*3 == 3+6j +assert isclose((1+2j)*(3+4j), -5+10j) +assert isclose((1+2j)*3, 3+6j) -import cmath - -assert (1+2j)**2 == -3+4j +assert isclose((1+2j)**2, -3+4j) assert (1+2j).conjugate() == 1-2j -res = cmath.sqrt(1+2j) -assert res == 1.272019649514069+0.7861513777574233j +res = sqrt(1+2j) +assert isclose(res, 1.272019649514069+0.7861513777574233j) + +assert {1+2j: 1}[1+2j] == 1