Skip to content

Implement math.hypot and math.copysign #201

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 4 commits into from
Mar 6, 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
15 changes: 14 additions & 1 deletion integration_tests/test_math_02.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from math import (sin, cos, tan, pi, sqrt, log, log10, log2, erf, erfc, gamma,
lgamma, asin, acos, atan, atan2, asinh, acosh, atanh,
tanh, sinh, cosh)
tanh, sinh, cosh, hypot, copysign)

def test_trig():
# TODO: importing from `math` doesn't work here yet:
Expand Down Expand Up @@ -46,7 +46,20 @@ def test_hyperbolic():
assert abs(cosh(1.0) - 0) < eps
assert abs(tanh(0.0) - 0) < eps

def test_copysign():
eps: f64 = 1e-12
assert abs(copysign(-8.56, 97.21) - 8.56) < eps
assert abs(copysign(-43.0, -76.67) - (-43.0)) < eps

def test_hypot():
eps: f64 = 1e-12
assert abs(hypot(3, 4) - 5.0) < eps
assert abs(hypot(-3, 4) - 5.0) < eps
assert abs(hypot(6, 6) - 8.48528137423857) < eps

test_trig()
test_sqrt()
test_log()
test_special()
test_copysign()
test_hypot()
18 changes: 18 additions & 0 deletions src/runtime/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,24 @@ def lcm(a: i32, b: i32) -> i32:
return 0
return (a*b)//gcd(a, b)


def copysign(x: f64, y: f64) -> f64:
"""
Return `x` with the sign of `y`.
"""
if y > 0.0 or (y == 0.0 and atan2(y, -1.0) > 0.0):
return fabs(x)
else:
return -fabs(x)


def hypot(x: i32, y: i32) -> f64:
"""
Returns the hypotenuse of the right triangle with sides `x` and `y`.
"""
return sqrt(1.0*(x**2 + y**2))


def sqrt(x: f64) -> f64:
return x**(1/2)

Expand Down