Explorar o código

fix https://github.com/pocketpy/pocketpy/issues/382

blueloveTH hai 8 meses
pai
achega
81679b740e
Modificáronse 3 ficheiros con 35 adicións e 4 borrados
  1. 0 4
      src/modules/math.c
  2. 30 0
      src/public/py_number.c
  3. 5 0
      tests/02_float.py

+ 0 - 4
src/modules/math.c

@@ -1,8 +1,4 @@
 #include "pocketpy/pocketpy.h"
-
-#include "pocketpy/common/utils.h"
-#include "pocketpy/objects/object.h"
-#include "pocketpy/common/sstream.h"
 #include "pocketpy/interpreter/vm.h"
 
 #include <math.h>

+ 30 - 0
src/public/py_number.c

@@ -175,6 +175,32 @@ static bool int__mod__(int argc, py_Ref argv) {
     return true;
 }
 
+static bool float__mod__(int argc, py_Ref argv) {
+    PY_CHECK_ARGC(2);
+    py_f64 lhs = py_tofloat(&argv[0]);
+    py_f64 rhs;
+    if(try_castfloat(&argv[1], &rhs)) {
+        if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
+        py_newfloat(py_retval(), fmod(lhs, rhs));
+        return true;
+    }
+    py_newnotimplemented(py_retval());
+    return true;
+}
+
+static bool float__rmod__(int argc, py_Ref argv) {
+    PY_CHECK_ARGC(2);
+    py_f64 rhs = py_tofloat(&argv[0]);
+    py_f64 lhs;
+    if(try_castfloat(&argv[1], &lhs)) {
+        if(rhs == 0.0) return ZeroDivisionError("float modulo by zero");
+        py_newfloat(py_retval(), fmod(lhs, rhs));
+        return true;
+    }
+    py_newnotimplemented(py_retval());
+    return true;
+}
+
 static bool int__divmod__(int argc, py_Ref argv) {
     PY_CHECK_ARGC(2);
     PY_CHECK_ARG_TYPE(1, tp_int);
@@ -508,6 +534,10 @@ void pk_number__register() {
     py_bindmagic(tp_int, __mod__, int__mod__);
     py_bindmagic(tp_int, __divmod__, int__divmod__);
 
+    // fmod
+    py_bindmagic(tp_float, __mod__, float__mod__);
+    py_bindmagic(tp_float, __rmod__, float__rmod__);
+
     // int.__invert__ & int.<BITWISE OP>
     py_bindmagic(tp_int, __invert__, int__invert__);
 

+ 5 - 0
tests/02_float.py

@@ -109,3 +109,8 @@ assert abs(0.0) == 0.0
 #     exit(1)
 # except ValueError:
 #     pass
+
+assert eq(10 % 4, 2)
+assert eq(10.5 % 4, 2.5)
+assert eq(10 % 4.5, 1.0)
+assert eq(10.5 % 4.5, 1.5)