Skip to content

Commit 6db4249

Browse files
feat: menambahkan algoritma rieman
1 parent ce827e3 commit 6db4249

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

math/rieman_integral.py

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
from typing import Callable
2+
import math
3+
4+
5+
def rieman_integral(f: Callable[[float], float],
6+
a: float,
7+
b: float,
8+
n: int,
9+
approx: str) -> float:
10+
"""
11+
>>> rieman_integral(math.sin,0,math.pi/2,100,"tengah")
12+
1.0000102809119051
13+
>>> rieman_integral(math.sin,0,math.pi/2,100,"kanan")
14+
1.007833419873582
15+
>>> rieman_integral(math.sin,0,math.pi/2,100,"kiri")
16+
0.9921254566056331
17+
"""
18+
delta_x = (b - a) / n
19+
sigma = 0.0
20+
approx = approx.lower()
21+
22+
for i in range(n):
23+
left = a + i * delta_x
24+
right = left + delta_x
25+
26+
if approx == "kiri":
27+
x_i = left
28+
elif approx == "kanan":
29+
x_i = right
30+
elif approx == "tengah":
31+
x_i = left + 0.5 * delta_x
32+
else:
33+
raise ValueError("masukkan approx benar")
34+
35+
sigma += f(x_i)
36+
37+
return delta_x * sigma
38+
39+
40+
def main(args=None):
41+
import doctest
42+
43+
doctest.testmod()
44+
45+
# persamaan x
46+
def f(x):
47+
return x
48+
print(rieman_integral(f, 0, 1, 1, "tengah")) # 0.5
49+
50+
# persamaan 4/(1+x^2)
51+
def f(x):
52+
return (4) / (1 + x**2)
53+
print(rieman_integral(f, 0, 1, 1000, "tengah")) # 3.1415927369231227
54+
55+
# Persamaan sin
56+
def f(x):
57+
return math.sin(x)
58+
print(rieman_integral(f, 0, math.pi / 2, 100, "kiri")) # 0.9921254566056331
59+
60+
61+
if __name__ == "__main__":
62+
main()

0 commit comments

Comments
 (0)