Skip to content
This repository was archived by the owner on Sep 6, 2023. It is now read-only.

Commit 561844f

Browse files
committed
py: Add MICROPY_FLOAT_CONST macro for defining float constants.
All float constants in the core should use this macro to prevent unnecessary creation of double-precision floats, which makes code less efficient.
1 parent ca973bd commit 561844f

File tree

3 files changed

+7
-6
lines changed

3 files changed

+7
-6
lines changed

py/modmath.c

+4-5
Original file line numberDiff line numberDiff line change
@@ -32,9 +32,8 @@
3232
#include <math.h>
3333

3434
// M_PI is not part of the math.h standard and may not be defined
35-
#ifndef M_PI
36-
#define M_PI (3.14159265358979323846)
37-
#endif
35+
// And by defining our own we can ensure it uses the correct const format.
36+
#define MP_PI MICROPY_FLOAT_CONST(3.14159265358979323846)
3837

3938
/// \module math - mathematical functions
4039
///
@@ -204,13 +203,13 @@ STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_modf_obj, mp_math_modf);
204203

205204
/// \function radians(x)
206205
STATIC mp_obj_t mp_math_radians(mp_obj_t x_obj) {
207-
return mp_obj_new_float(mp_obj_get_float(x_obj) * M_PI / 180.0);
206+
return mp_obj_new_float(mp_obj_get_float(x_obj) * (MP_PI / MICROPY_FLOAT_CONST(180.0)));
208207
}
209208
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_radians_obj, mp_math_radians);
210209

211210
/// \function degrees(x)
212211
STATIC mp_obj_t mp_math_degrees(mp_obj_t x_obj) {
213-
return mp_obj_new_float(mp_obj_get_float(x_obj) * 180.0 / M_PI);
212+
return mp_obj_new_float(mp_obj_get_float(x_obj) * (MICROPY_FLOAT_CONST(180.0) / MP_PI));
214213
}
215214
STATIC MP_DEFINE_CONST_FUN_OBJ_1(mp_math_degrees_obj, mp_math_degrees);
216215

py/mpconfig.h

+2
Original file line numberDiff line numberDiff line change
@@ -505,10 +505,12 @@ typedef long long mp_longint_impl_t;
505505

506506
#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT
507507
#define MICROPY_PY_BUILTINS_FLOAT (1)
508+
#define MICROPY_FLOAT_CONST(x) x##F
508509
#define MICROPY_FLOAT_C_FUN(fun) fun##f
509510
typedef float mp_float_t;
510511
#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE
511512
#define MICROPY_PY_BUILTINS_FLOAT (1)
513+
#define MICROPY_FLOAT_CONST(x) x
512514
#define MICROPY_FLOAT_C_FUN(fun) fun
513515
typedef double mp_float_t;
514516
#else

py/parsenum.c

+1-1
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool
227227
} else {
228228
if (in == PARSE_DEC_IN_FRAC) {
229229
dec_val += dig * frac_mult;
230-
frac_mult *= 0.1;
230+
frac_mult *= MICROPY_FLOAT_CONST(0.1);
231231
} else {
232232
dec_val = 10 * dec_val + dig;
233233
}

0 commit comments

Comments
 (0)