From 5e4acd75943640a3d1a12d217950ee8880a1a413 Mon Sep 17 00:00:00 2001 From: Smit-create Date: Wed, 9 Nov 2022 18:11:47 +0530 Subject: [PATCH 1/2] Add `dist` in math Co-Authored-By: Aastha Singh --- src/runtime/math.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/runtime/math.py b/src/runtime/math.py index 8550102659..a91ff0da89 100644 --- a/src/runtime/math.py +++ b/src/runtime/math.py @@ -207,6 +207,21 @@ def prod(arr: list[f64]) -> f64: return result +def dist(x: list[f64], y: list[f64]) -> f64: + """ + Return euclidean distance between `x` and `y` points. + """ + if len(x) != len(y): + raise ValueError("Length of lists should be same") + res: f64 + res = 0.0 + + i: i32 + for i in range(len(x)): + res += (x[i] - y[i]) ** 2 + return res**0.5 + + def comb(n: i32, k: i32) -> i32: """ Computes the result of `nCk`, i.e, the number of ways to choose `k` From 96a36cecf2b3a85d6c754cbe439f75aa9d7e9066 Mon Sep 17 00:00:00 2001 From: Smit-create Date: Sun, 27 Nov 2022 01:33:23 +0530 Subject: [PATCH 2/2] Add tests Co-Authored-By: Aastha Singh --- integration_tests/test_math.py | 11 ++++++++++- src/runtime/math.py | 2 +- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/integration_tests/test_math.py b/integration_tests/test_math.py index d69406fc8c..315b4efb8e 100644 --- a/integration_tests/test_math.py +++ b/integration_tests/test_math.py @@ -1,6 +1,6 @@ from math import (factorial, isqrt, perm, comb, degrees, radians, exp, pow, ldexp, fabs, gcd, lcm, floor, ceil, remainder, expm1, fmod, log1p, trunc, - modf, fsum, prod) + modf, fsum, prod, dist) import math from ltypes import i32, i64, f32, f64 @@ -220,6 +220,14 @@ def test_prod(): res = prod(arr_f64) assert abs(res - 80.64) < eps +def test_dist(): + x: list[f64] + y: list[f64] + eps: f64 = 1e-12 + x = [1.0, 2.2, 3.333, 4.0, 5.0] + y = [6.1, 7.2, 8.0, 9.0, 10.0] + assert abs(dist(x, y) - 11.081105044173166) < eps + def test_modf(): i: f64 i = 3.14 @@ -268,6 +276,7 @@ def check(): test_trunc() test_fsum() test_prod() + test_dist() test_modf() test_issue_1242() diff --git a/src/runtime/math.py b/src/runtime/math.py index a91ff0da89..379581c528 100644 --- a/src/runtime/math.py +++ b/src/runtime/math.py @@ -218,7 +218,7 @@ def dist(x: list[f64], y: list[f64]) -> f64: i: i32 for i in range(len(x)): - res += (x[i] - y[i]) ** 2 + res += (x[i] - y[i]) * (x[i] - y[i]) return res**0.5