Skip to content

Commit d33c16f

Browse files
authored
Merge pull request #128 from Smit-create/math2
Add more math functions
2 parents b83c06c + ebbe72d commit d33c16f

File tree

2 files changed

+101
-4
lines changed

2 files changed

+101
-4
lines changed

integration_tests/test_math.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,44 @@
1-
from math import factorial
1+
from math import factorial, isqrt, perm, comb, degrees, radians
2+
from ltypes import i32, f64
23

34
def test_factorial_1():
45
i: i32
56
i = factorial(10)
67
print(i)
78

9+
10+
def test_comb():
11+
i: i32
12+
i = comb(10, 2)
13+
print(i)
14+
15+
16+
def test_perm():
17+
i: i32
18+
i = perm(5, 2)
19+
20+
21+
def test_isqrt():
22+
i: i32
23+
i = isqrt(15)
24+
print(i)
25+
26+
27+
def test_degrees():
28+
i: f64
29+
i = degrees(32.2)
30+
print(i)
31+
32+
33+
def test_radians():
34+
i: f64
35+
i = degrees(100.1)
36+
print(i)
37+
38+
839
test_factorial_1()
40+
test_comb()
41+
test_isqrt()
42+
test_perm()
43+
test_degrees()
44+
test_radians()

src/runtime/math.py

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
from ltypes import i32, f64
2+
3+
def pi() -> f64:
4+
return 3.141592653589793238462643383279502884197
5+
16
def factorial(x: i32) -> i32:
27
"""
38
Computes the factorial of `x`.
@@ -7,7 +12,63 @@ def factorial(x: i32) -> i32:
712
return 0
813
result: i32
914
result = 1
10-
while x > 0:
11-
result = result * x
12-
x -= 1
15+
i: i32
16+
for i in range(1, x+1):
17+
result *= i
1318
return result
19+
20+
21+
def comb(n: i32, k: i32) -> i32:
22+
"""
23+
Computes the result of `nCk`, i.e, the number of ways to choose `k`
24+
items from `n` items without repetition and without order.
25+
"""
26+
27+
if n < k or n < 0:
28+
return 0
29+
return factorial(n)//(factorial(k)*factorial(n-k))
30+
31+
32+
def perm(n: i32, k: i32) -> i32:
33+
"""
34+
Computes the result of `nPk`, i.e, the number of ways to choose `k` items
35+
from `n` items without repetition and with order.
36+
"""
37+
38+
if n < k or n < 0:
39+
return 0
40+
return factorial(n)//factorial(n-k)
41+
42+
43+
def isqrt(n: i32) -> i32:
44+
"""
45+
Computes the integer square root of the nonnegative integer `n`.
46+
"""
47+
if n < 0:
48+
raise ValueError('`n` should be nonnegative')
49+
low: i32
50+
mid: i32
51+
high: i32
52+
low = 0
53+
high = n+1
54+
while low + 1 < high:
55+
mid = (low + high)//2
56+
if mid*mid <= n:
57+
low = mid
58+
else:
59+
high = mid
60+
return low
61+
62+
63+
def degrees(x: f64) -> f64:
64+
"""
65+
Convert angle `x` from radians to degrees.
66+
"""
67+
return x * 180.0 / pi()
68+
69+
70+
def radians(x: f64) -> f64:
71+
"""
72+
Convert angle `x` from degrees to radians.
73+
"""
74+
return x * pi() / 180.0

0 commit comments

Comments
 (0)