diff --git a/python_test.py b/python_test.py new file mode 100644 index 000000000..4f48b3d26 --- /dev/null +++ b/python_test.py @@ -0,0 +1,5 @@ +import math + + +print(math.frexp("sdf")) +print(math.ldexp(0.95, 2)) diff --git a/tests/snippets/math_module.py b/tests/snippets/math_module.py index 8f5f9028d..546212cd4 100644 --- a/tests/snippets/math_module.py +++ b/tests/snippets/math_module.py @@ -84,6 +84,11 @@ assert str(math.frexp(-0.0)) == str((-0.0, 0)) assert math.frexp(1) == (0.5, 1) assert math.frexp(1.5) == (0.75, 1) +assert str(math.ldexp(+0.0, 0)) == str(0.0) +assert str(math.ldexp(-0.0, 0)) == str(-0.0) +assert math.ldexp(0.5, 1) == 1 +assert math.ldexp(0.75, 1) == 1.5 + assert math.frexp(float('inf')) == (float('inf'), 0) assert str(math.frexp(float('nan'))) == str((float('nan'), 0)) assert_raises(TypeError, lambda: math.frexp(None)) diff --git a/vm/src/stdlib/math.rs b/vm/src/stdlib/math.rs index a4ccd1fef..9ed5a63b4 100644 --- a/vm/src/stdlib/math.rs +++ b/vm/src/stdlib/math.rs @@ -8,6 +8,7 @@ use statrs::function::gamma::{gamma, ln_gamma}; use num_bigint::BigInt; use num_traits::{One, Zero}; +use num_traits::cast::ToPrimitive; use crate::function::PyFuncArgs; use crate::obj::objint::PyIntRef; @@ -229,6 +230,14 @@ fn math_frexp(value: PyObjectRef, vm: &VirtualMachine) -> PyResult { ) } +fn math_ldexp(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult { + arg_check!(vm, args, required = [(value, None), (i, None)]); + let value = objfloat::make_float(vm, value)?; + let i = objint::get_value(i); + Ok(vm.ctx.new_float(value * (2 as f64).powf(i.to_f64().unwrap()))) +} + + fn math_gcd(a: PyIntRef, b: PyIntRef, vm: &VirtualMachine) -> PyResult { use num_integer::Integer; Ok(vm.new_int(a.as_bigint().gcd(b.as_bigint()))) @@ -294,6 +303,7 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef { "lgamma" => ctx.new_rustfunc(math_lgamma), "frexp" => ctx.new_rustfunc(math_frexp), + "ldexp" => ctx.new_rustfunc(math_ldexp), // Rounding functions: "trunc" => ctx.new_rustfunc(math_trunc),