Skip to content

Commit 69c255f

Browse files
authored
Merge pull request #201 from namannimmo10/math1
Implement `math.hypot` and `math.copysign`
2 parents e709f9f + d88919c commit 69c255f

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

integration_tests/test_math_02.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
from math import (sin, cos, tan, pi, sqrt, log, log10, log2, erf, erfc, gamma,
22
lgamma, asin, acos, atan, atan2, asinh, acosh, atanh,
3-
tanh, sinh, cosh)
3+
tanh, sinh, cosh, hypot, copysign)
44

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

49+
def test_copysign():
50+
eps: f64 = 1e-12
51+
assert abs(copysign(-8.56, 97.21) - 8.56) < eps
52+
assert abs(copysign(-43.0, -76.67) - (-43.0)) < eps
53+
54+
def test_hypot():
55+
eps: f64 = 1e-12
56+
assert abs(hypot(3, 4) - 5.0) < eps
57+
assert abs(hypot(-3, 4) - 5.0) < eps
58+
assert abs(hypot(6, 6) - 8.48528137423857) < eps
59+
4960
test_trig()
5061
test_sqrt()
5162
test_log()
5263
test_special()
64+
test_copysign()
65+
test_hypot()

src/runtime/math.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,24 @@ def lcm(a: i32, b: i32) -> i32:
140140
return 0
141141
return (a*b)//gcd(a, b)
142142

143+
144+
def copysign(x: f64, y: f64) -> f64:
145+
"""
146+
Return `x` with the sign of `y`.
147+
"""
148+
if y > 0.0 or (y == 0.0 and atan2(y, -1.0) > 0.0):
149+
return fabs(x)
150+
else:
151+
return -fabs(x)
152+
153+
154+
def hypot(x: i32, y: i32) -> f64:
155+
"""
156+
Returns the hypotenuse of the right triangle with sides `x` and `y`.
157+
"""
158+
return sqrt(1.0*(x**2 + y**2))
159+
160+
143161
def sqrt(x: f64) -> f64:
144162
return x**(1/2)
145163

0 commit comments

Comments
 (0)