Răsfoiți Sursa

support `abs()` for complex objects

BLUELOVETH 1 an în urmă
părinte
comite
981e6e6e88
5 a modificat fișierele cu 7 adăugiri și 6 ștergeri
  1. 1 0
      include/pocketpy/str.h
  2. 4 4
      python/cmath.py
  3. 0 0
      src/_generated.cpp
  4. 1 2
      src/pocketpy.cpp
  5. 1 0
      src/str.cpp

+ 1 - 0
include/pocketpy/str.h

@@ -224,6 +224,7 @@ extern const StrName __package__;
 extern const StrName __path__;
 extern const StrName __class__;
 extern const StrName __missing__;
+extern const StrName __abs__;
 
 extern const StrName pk_id_add;
 extern const StrName pk_id_set;

+ 4 - 4
python/cmath.py

@@ -77,8 +77,8 @@ class complex:
     
     def __pow__(self, other: int | float):
         if type(other) in (int, float):
-            return complex(self.__abs__() ** other * math.cos(other * phase(self)),
-                           self.__abs__() ** other * math.sin(other * phase(self)))
+            return complex(abs(self) ** other * math.cos(other * phase(self)),
+                           abs(self) ** other * math.sin(other * phase(self)))
         return NotImplemented
     
     def __abs__(self) -> float:
@@ -97,7 +97,7 @@ def phase(z: complex):
     return math.atan2(z.imag, z.real)
 
 def polar(z: complex):
-    return z.__abs__(), phase(z)
+    return abs(z), phase(z)
 
 def rect(r: float, phi: float):
     return r * math.cos(phi) + r * math.sin(phi) * 1j
@@ -108,7 +108,7 @@ def exp(z: complex):
     return math.exp(z.real) * rect(1, z.imag)
 
 def log(z: complex, base=2.718281828459045):
-    return math.log(z.__abs__(), base) + phase(z) * 1j
+    return math.log(abs(z), base) + phase(z) * 1j
 
 def log10(z: complex):
     return log(z, 10)

Fișier diff suprimat deoarece este prea mare
+ 0 - 0
src/_generated.cpp


+ 1 - 2
src/pocketpy.cpp

@@ -158,8 +158,7 @@ void __init_builtins(VM* _vm) {
     _vm->bind_func(_vm->builtins, "abs", 1, [](VM* vm, ArgsView args) {
         if(is_int(args[0])) return VAR(std::abs(_CAST(i64, args[0])));
         if(is_float(args[0])) return VAR(std::abs(_CAST(f64, args[0])));
-        vm->TypeError("bad operand type for abs()");
-        return vm->None;
+        return vm->call_method(args[0], __abs__);
     });
 
     _vm->bind(_vm->builtins, "max(*args, key=None)", [](VM* vm, ArgsView args){

+ 1 - 0
src/str.cpp

@@ -592,6 +592,7 @@ const StrName __package__ = StrName::get("__package__");
 const StrName __path__ = StrName::get("__path__");
 const StrName __class__ = StrName::get("__class__");
 const StrName __missing__ = StrName::get("__missing__");
+const StrName __abs__ = StrName::get("__abs__");
 
 const StrName pk_id_add = StrName::get("add");
 const StrName pk_id_set = StrName::get("set");

Unele fișiere nu au fost afișate deoarece prea multe fișiere au fost modificate în acest diff