Skip to content

Commit c3714c2

Browse files
committed
Add math.trunc
1 parent 53dea48 commit c3714c2

File tree

2 files changed

+42
-2
lines changed

2 files changed

+42
-2
lines changed

tests/snippets/math_basics.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
import math
2+
from testutils import assertRaises
3+
14
a = 4
25

36
#print(a ** 3)
@@ -17,7 +20,6 @@
1720
assert -a == -4
1821
assert +a == 4
1922

20-
# import math
2123
# assert(math.exp(2) == math.exp(2.0))
2224
# assert(math.exp(True) == math.exp(1.0))
2325
#
@@ -27,3 +29,24 @@
2729
# return 1.1111
2830
#
2931
# assert math.log(1.1111) == math.log(Conversible())
32+
33+
# roundings
34+
assert math.trunc(1) == 1
35+
36+
class A(object):
37+
def __trunc__(self):
38+
return 2
39+
40+
assert math.trunc(A()) == 2
41+
42+
class A(object):
43+
def __trunc__(self):
44+
return 2.0
45+
46+
assert math.trunc(A()) == 2.0
47+
48+
class A(object):
49+
def __trunc__(self):
50+
return 'str'
51+
52+
assert math.trunc(A()) == 'str'

vm/src/stdlib/math.rs

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use statrs::function::gamma::{gamma, ln_gamma};
88

99
use crate::function::PyFuncArgs;
1010
use crate::obj::objfloat;
11-
use crate::pyobject::{PyObjectRef, PyResult};
11+
use crate::pyobject::{PyObjectRef, PyResult, TypeProtocol};
1212
use crate::vm::VirtualMachine;
1313

1414
// Helper macro:
@@ -172,6 +172,20 @@ fn math_lgamma(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
172172
}
173173
}
174174

175+
fn math_trunc(vm: &VirtualMachine, args: PyFuncArgs) -> PyResult {
176+
arg_check!(vm, args, required = [(value, None)]);
177+
const MAGIC_NAME: &str = "__trunc__";
178+
if let Ok(method) = vm.get_method(value.clone(), MAGIC_NAME) {
179+
vm.invoke(method, vec![])
180+
} else {
181+
Err(vm.new_type_error(format!(
182+
"TypeError: type {} doesn't define {} method",
183+
value.class().name,
184+
MAGIC_NAME,
185+
)))
186+
}
187+
}
188+
175189
pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
176190
let ctx = &vm.ctx;
177191

@@ -219,6 +233,9 @@ pub fn make_module(vm: &VirtualMachine) -> PyObjectRef {
219233
"gamma" => ctx.new_rustfunc(math_gamma),
220234
"lgamma" => ctx.new_rustfunc(math_lgamma),
221235

236+
// Rounding functions:
237+
"trunc" => ctx.new_rustfunc(math_trunc),
238+
222239
// Constants:
223240
"pi" => ctx.new_float(std::f64::consts::PI), // 3.14159...
224241
"e" => ctx.new_float(std::f64::consts::E), // 2.71..

0 commit comments

Comments
 (0)