-
-
Notifications
You must be signed in to change notification settings - Fork 107
Expand file tree
/
Copy pathpendulum.py
More file actions
96 lines (77 loc) · 2.39 KB
/
pendulum.py
File metadata and controls
96 lines (77 loc) · 2.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# https://en.wikipedia.org/wiki/Pendulum
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# parameter awal
g = 9.8 # konstanta gravitasi
L = 1.0 # panjang tali
time_step = 20 / 300
time_stap = np.linspace(0, 20, 300)
def full_pendulum(g, L, theta, theta_velocity, time_step):
"""
fungsi untuk menghitung persamaan pendulum.
"""
theta_acceleration = -(g / L) * np.sin(theta)
theta_velocity += time_step * theta_acceleration
theta += time_step * theta_velocity
return theta, theta_velocity
def calculate_pendulum():
theta = [np.radians(90)]
theta_velocity = 0
for _ in time_stap:
theta_new, theta_velocity = full_pendulum(g, L, theta[-1],
theta_velocity, time_step)
theta.append(theta_new)
# persamaan proyeksi panjang tali
x = L * np.sin(theta)
y = -L * np.cos(theta)
return x, y
def setup_axis(axis) -> None:
"""
Setup sumbu x dan y.
"""
axis.set_xlim(-L - 0.2 , L + 0.2)
axis.set_ylim(-L - 0.2 , L)
axis.grid()
return axis
def create_plot_elements(axis) -> None:
"""
Membuat elemen plot yang akan dianimasu.
"""
rod_line, = axis.plot([], [], lw=2)
mass_point, = axis.plot([], [], marker='o', markersize=10)
trace, = axis.plot([], [], '-', lw=1, alpha=0.6)
return rod_line, mass_point, trace
def animate(frame, x, y, rod_line, mass_point, trace) -> None:
"""
Fungsi ini berguna untuk mengambil setiap hasil hitungan
dan menjadikan setiap hitungan frame.
"""
rod_line.set_data([0, x[frame]], [0, y[frame]])
mass_point.set_data([x[frame]], [y[frame]])
trace.set_data(x[:frame], y[:frame])
return rod_line, mass_point, trace
if __name__ == "__main__":
x, y = calculate_pendulum()
fig, axis = plt.subplots()
axis = setup_axis(axis)
rod_line, mass_point, trace = create_plot_elements(axis)
def init():
"""
Parameter awal.
"""
rod_line.set_data([], [])
mass_point.set_data([], [])
trace.set_data([], [])
return rod_line, mass_point, trace
animation = FuncAnimation(
fig=fig,
func=animate,
fargs=(x, y, rod_line, mass_point, trace),
init_func=init,
frames=len(time_stap),
interval=25,
blit=True
)
print(animation)
plt.show()