Skip to content

Add dist() function in math.py #456

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

Merged
merged 2 commits into from
Dec 8, 2022
Merged
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
11 changes: 10 additions & 1 deletion integration_tests/test_math.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -268,6 +276,7 @@ def check():
test_trunc()
test_fsum()
test_prod()
test_dist()
test_modf()
test_issue_1242()

Expand Down
15 changes: 15 additions & 0 deletions src/runtime/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]) * (x[i] - y[i])
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`
Expand Down