Skip to content

Commit 533aa2b

Browse files
author
johan.park
committed
Update fmod module of math
- Implement fmod function with test case
1 parent ff54fc8 commit 533aa2b

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

tests/snippets/stdlib_math.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -246,3 +246,23 @@ def assertAllNotClose(examples, *args, **kwargs):
246246
modf_nan = math.modf(NAN)
247247
assert math.isnan(modf_nan[0])
248248
assert math.isnan(modf_nan[1])
249+
250+
assert math.fmod(10, 1) == 0.0
251+
assert math.fmod(10, 0.5) == 0.0
252+
assert math.fmod(10, 1.5) == 1.0
253+
assert math.fmod(-10, 1) == -0.0
254+
assert math.fmod(-10, 0.5) == -0.0
255+
assert math.fmod(-10, 1.5) == -1.0
256+
assert math.isnan(math.fmod(NAN, 1.)) == True
257+
assert math.isnan(math.fmod(1., NAN)) == True
258+
assert math.isnan(math.fmod(NAN, NAN)) == True
259+
assert_raises(ValueError, lambda: math.fmod(1., 0.))
260+
assert_raises(ValueError, lambda: math.fmod(INF, 1.))
261+
assert_raises(ValueError, lambda: math.fmod(NINF, 1.))
262+
assert_raises(ValueError, lambda: math.fmod(INF, 0.))
263+
assert math.fmod(3.0, INF) == 3.0
264+
assert math.fmod(-3.0, INF) == -3.0
265+
assert math.fmod(3.0, NINF) == 3.0
266+
assert math.fmod(-3.0, NINF) == -3.0
267+
assert math.fmod(0.0, 3.0) == 0.0
268+
assert math.fmod(0.0, NINF) == 0.0

vm/src/stdlib/math.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,20 @@ fn math_modf(x: IntoPyFloat, _vm: &VirtualMachine) -> (f64, f64) {
275275
(x.fract(), x.trunc())
276276
}
277277

278+
fn math_fmod(x: IntoPyFloat, y: IntoPyFloat, vm: &VirtualMachine) -> PyResult<f64> {
279+
let x = x.to_f64();
280+
let y = y.to_f64();
281+
if y.is_infinite() && x.is_finite() {
282+
return Ok(x);
283+
}
284+
let r = x % y;
285+
if r.is_nan() && !x.is_nan() && !y.is_nan() {
286+
return Err(vm.new_value_error("math domain error".to_string()));
287+
}
288+
289+
Ok(r)
290+
}
291+
278292
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
279293
let ctx = &vm.ctx;
280294

@@ -327,6 +341,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
327341
"frexp" => ctx.new_rustfunc(math_frexp),
328342
"ldexp" => ctx.new_rustfunc(math_ldexp),
329343
"modf" => ctx.new_rustfunc(math_modf),
344+
"fmod" => ctx.new_rustfunc(math_fmod),
330345

331346
// Rounding functions:
332347
"trunc" => ctx.new_rustfunc(math_trunc),

0 commit comments

Comments
 (0)