This commit is contained in:
blueloveTH 2023-12-30 20:58:52 +08:00
parent 2898fbd5cb
commit 889cf99695
3 changed files with 20 additions and 12 deletions

View File

@ -1,4 +1,4 @@
from typing import overload, Generic, TypeVar from typing import Generic, TypeVar
def malloc(size: int) -> 'void_p': ... def malloc(size: int) -> 'void_p': ...
def free(ptr: 'void_p') -> None: ... def free(ptr: 'void_p') -> None: ...

View File

@ -21,9 +21,9 @@ class complex:
def __eq__(self, other): def __eq__(self, other):
if type(other) is complex: 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): 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 return NotImplemented
def __add__(self, other): def __add__(self, other):
@ -70,6 +70,9 @@ class complex:
def __abs__(self) -> float: def __abs__(self) -> float:
return math.sqrt(self.real ** 2 + self.imag ** 2) return math.sqrt(self.real ** 2 + self.imag ** 2)
def __hash__(self):
return hash((self.real, self.imag))
# Conversions to and from polar coordinates # Conversions to and from polar coordinates
@ -147,6 +150,9 @@ def isinf(z: complex):
def isnan(z: complex): def isnan(z: complex):
return math.isnan(z.real) or math.isnan(z.imag) 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 # Constants
pi = math.pi pi = math.pi

View File

@ -1,20 +1,22 @@
from cmath import isclose, sqrt
assert 1+2j == complex(1, 2) == 2j+1 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).real == 1
assert (1+2j).imag == 2 assert (1+2j).imag == 2
assert (1+2j)*(3+4j) == -5+10j assert isclose((1+2j)*(3+4j), -5+10j)
assert (1+2j)*3 == 3+6j assert isclose((1+2j)*3, 3+6j)
import cmath assert isclose((1+2j)**2, -3+4j)
assert (1+2j)**2 == -3+4j
assert (1+2j).conjugate() == 1-2j assert (1+2j).conjugate() == 1-2j
res = cmath.sqrt(1+2j) res = sqrt(1+2j)
assert res == 1.272019649514069+0.7861513777574233j assert isclose(res, 1.272019649514069+0.7861513777574233j)
assert {1+2j: 1}[1+2j] == 1