Skip to content

py/modmath: New function math hypot. #8593

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions py/modmath.c
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,24 @@ MATH_FUN_1(erfc, erfc)
MATH_FUN_1(gamma, tgamma)
// lgamma(x): return the natural logarithm of the gamma function of x
MATH_FUN_1(lgamma, lgamma)

STATIC mp_obj_t mp_math_hypot(size_t n_args, const mp_obj_t *args) {
mp_float_t a;
mp_float_t a_pow2;
mp_float_t ans;
ans = (mp_float_t)0.0;
for (size_t i = 0; i < n_args; i++) {
a = mp_obj_get_float(args[i]);
a_pow2 = MICROPY_FLOAT_C_FUN(pow)(a, 2);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it be more efficient to just do ans += a * a instead of calling pow?

ans += a_pow2;
}
return mp_obj_new_float(MICROPY_FLOAT_C_FUN(sqrt)(ans));
}

MP_DEFINE_CONST_FUN_OBJ_VAR(mp_math_hypot_obj, 2, mp_math_hypot);

#endif

// TODO: fsum

#if MICROPY_PY_MATH_ISCLOSE
Expand Down Expand Up @@ -425,6 +442,7 @@ STATIC const mp_rom_map_elem_t mp_module_math_globals_table[] = {
{ MP_ROM_QSTR(MP_QSTR_erfc), MP_ROM_PTR(&mp_math_erfc_obj) },
{ MP_ROM_QSTR(MP_QSTR_gamma), MP_ROM_PTR(&mp_math_gamma_obj) },
{ MP_ROM_QSTR(MP_QSTR_lgamma), MP_ROM_PTR(&mp_math_lgamma_obj) },
{ MP_ROM_QSTR(MP_QSTR_hypot), MP_ROM_PTR(&mp_math_hypot_obj) },
#endif
};

Expand Down
17 changes: 17 additions & 0 deletions tests/float/math_fun_special.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,20 @@
print("{:.4g}".format(function(value)))
except ValueError as e:
print(str(e))

hypot_func_var_args = [
(
"hypot",
hypot,
(
(12.0, 5.0),
(12, 5),
(bool(1), bool(0), bool(1), bool(1)),
(0.0, 0.0),
(-10.5),
(),
(1.5, 1.5, 0.5),
(1.5, 0.5, 1.5),
),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add tests for NaN and infinity arguments and return values?

),
]