diff --git a/src/modules/math.c b/src/modules/math.c index 294350e7..4ef3f81e 100644 --- a/src/modules/math.c +++ b/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 diff --git a/src/public/py_number.c b/src/public/py_number.c index b07f2cc2..7e0bd5d6 100644 --- a/src/public/py_number.c +++ b/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. py_bindmagic(tp_int, __invert__, int__invert__); diff --git a/tests/02_float.py b/tests/02_float.py index 06aadc6a..e2b4821c 100644 --- a/tests/02_float.py +++ b/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) \ No newline at end of file