diff options
author | Damien George <damien.p.george@gmail.com> | 2017-03-24 10:40:25 +1100 |
---|---|---|
committer | Damien George <damien.p.george@gmail.com> | 2017-03-24 11:00:45 +1100 |
commit | 125eae1ba3c59b882fc95c82c95dccd2d93ceaa1 (patch) | |
tree | 138c06938686efa732f61672ec6e2545633221d8 /py | |
parent | fb161aa45a8110d18b08efa3175027b8fbac5463 (diff) | |
download | micropython-125eae1ba3c59b882fc95c82c95dccd2d93ceaa1.tar.gz micropython-125eae1ba3c59b882fc95c82c95dccd2d93ceaa1.zip |
py/modbuiltins: For round() builtin use nearbyint instead of round.
The C nearbyint function has exactly the semantics that Python's round()
requires, whereas C's round() requires extra steps to handle rounding of
numbers half way between integers. So using nearbyint reduces code size
and potentially eliminates any source of errors in the handling of half-way
numbers.
Also, bare-metal implementations of nearbyint can be more efficient than
round, so further code size is saved (and efficiency improved).
nearbyint is provided in the C99 standard so it should be available on all
supported platforms.
Diffstat (limited to 'py')
-rw-r--r-- | py/modbuiltins.c | 11 |
1 files changed, 2 insertions, 9 deletions
diff --git a/py/modbuiltins.c b/py/modbuiltins.c index 13312d2296..541e733e5a 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -473,18 +473,11 @@ STATIC mp_obj_t mp_builtin_round(size_t n_args, const mp_obj_t *args) { mp_float_t val = mp_obj_get_float(o_in); mp_float_t mult = MICROPY_FLOAT_C_FUN(pow)(10, num_dig); // TODO may lead to overflow - mp_float_t rounded = MICROPY_FLOAT_C_FUN(round)(val * mult) / mult; + mp_float_t rounded = MICROPY_FLOAT_C_FUN(nearbyint)(val * mult) / mult; return mp_obj_new_float(rounded); } mp_float_t val = mp_obj_get_float(o_in); - mp_float_t rounded = MICROPY_FLOAT_C_FUN(round)(val); - mp_int_t r = rounded; - // make rounded value even if it was halfway between ints - if (val - rounded == 0.5) { - r = (r + 1) & (~1); - } else if (val - rounded == -0.5) { - r &= ~1; - } + mp_float_t rounded = MICROPY_FLOAT_C_FUN(nearbyint)(val); #else mp_int_t r = mp_obj_get_int(o_in); #endif |