8000 Merge pull request #9560 from FoamyGuy/math_dist · EternityForest/circuitpython@1039743 · GitHub
[go: up one dir, main page]

Skip to content

Commit 1039743

Browse files
authored
Merge pull request adafruit#9560 from FoamyGuy/math_dist
Implement math.dist
2 parents 30a4bd1 + e682663 commit 1039743

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

shared-bindings/math/__init__.c

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,34 @@ MATH_FUN_1(gamma, tgamma)
328328
//| ...
329329
//|
330330
MATH_FUN_1(lgamma, lgamma)
331+
332+
//| def dist(p: tuple, q: tuple) -> float:
333+
//| """Return the Euclidean distance between two points ``p`` and ``q``.
334+
//|
335+
//| May not be available on some boards.
336+
//| """
337+
//| ...
338+
//|
339+
static mp_obj_t mp_math_dist(mp_obj_t p_obj, mp_obj_t q_obj) {
340+
mp_obj_t *p_items;
341+
mp_obj_get_array_fixed_n(p_obj, 2, &p_items);
342+
343+
mp_obj_t *q_items;
344+
mp_obj_get_array_fixed_n(q_obj, 2, &q_items);
345+
346+
mp_float_t px_in = mp_obj_get_float(p_items[0]);
347+
mp_float_t py_in = mp_obj_get_float(p_items[1]);
348+
349+
mp_float_t qx_in = mp_obj_get_float(q_items[0]);
350+
mp_float_t qy_in = mp_obj_get_float(q_items[1]);
351+
352+
mp_float_t dist_x = px_in - qx_in;
353+
mp_float_t dist_y = py_in - qy_in;
354+
355+
return mp_obj_new_float(sqrtf((dist_x * dist_x) + (dist_y * dist_y)));
356+
}
357+
static MP_DEFINE_CONST_FUN_OBJ_2(mp_math_dist_obj, mp_math_dist);
358+
331359
#endif
332360
// TODO: factorial, fsum
333361

@@ -415,6 +443,7 @@ static const mp_rom_map_elem_t mp_module_math_globals_table[] = {
415443
{ MP_ROM_QSTR(MP_QSTR_acosh), MP_ROM_PTR(&mp_math_acosh_obj) },
416444
{ MP_ROM_QSTR(MP_QSTR_asinh), MP_ROM_PTR(&mp_math_asinh_obj) },
417445
{ MP_ROM_QSTR(MP_QSTR_atanh), MP_ROM_PTR(&mp_math_atanh_obj) },
446+
{ MP_ROM_QSTR(MP_QSTR_dist), MP_ROM_PTR(&mp_math_dist_obj) },
418447
#endif
419448
{ MP_ROM_QSTR(MP_QSTR_cos), MP_ROM_PTR(&mp_math_cos_obj) },
420449
{ MP_ROM_QSTR(MP_QSTR_sin), MP_ROM_PTR(&mp_math_sin_obj) },

0 commit comments

Comments
 (0)
0