Skip to content

Commit 45b1135

Browse files
committed
Implementation of math.remainder()
1 parent 76b8001 commit 45b1135

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/MathModuleBuiltins.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -854,6 +854,52 @@ protected void raiseMathDomainError(boolean con) {
854854

855855
}
856856

857+
@Builtin(name = "remainder", minNumOfPositionalArgs = 2)
858+
@TypeSystemReference(PythonArithmeticTypes.class)
859+
@ImportStatic(MathGuards.class)
860+
@GenerateNodeFactory
861+
public abstract static class RemainderNode extends PythonBinaryBuiltinNode {
862+
863+
@Specialization
864+
double remainderDD(double x, double y) {
865+
if (Double.isFinite(x) && Double.isFinite(y)) {
866+
if (y == 0.0) {
867+
throw raise(ValueError, ErrorMessages.MATH_DOMAIN_ERROR);
868+
}
869+
double absx = Math.abs(x);
870+
double absy = Math.abs(y);
871+
double m = absx % absy;
872+
double c = absy - m;
873+
double r;
874+
if (m < c) {
875+
r = m;
876+
} else if (m > c) {
877+
r = -c;
878+
} else {
879+
r = m - 2.0 * ((0.5 * (absx - m)) % absy);
880+
}
881+
return Math.copySign(1.0, x) * r;
882+
}
883+
if (Double.isNaN(x)) {
884+
return x;
885+
}
886+
if (Double.isNaN(y)) {
887+
return y;
888+
}
889+
if (Double.isInfinite(x)) {
890+
throw raise(ValueError, ErrorMessages.MATH_DOMAIN_ERROR);
891+
}
892+
return x;
893+
}
894+
895+
@Specialization(limit = "1")
896+
double remainderOO(Object x, Object y,
897+
@CachedLibrary("x") PythonObjectLibrary xLib,
898+
@CachedLibrary("y") PythonObjectLibrary yLib) {
899+
return remainderDD(xLib.asJavaDouble(x), yLib.asJavaDouble(y));
900+
}
901+
}
902+
857903
@Builtin(name = "frexp", minNumOfPositionalArgs = 1)
858904
@TypeSystemReference(PythonArithmeticTypes.class)
859905
@ImportStatic(MathGuards.class)

0 commit comments

Comments
 (0)