-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathEuler-2d.py
More file actions
78 lines (67 loc) · 2.4 KB
/
Copy pathEuler-2d.py
File metadata and controls
78 lines (67 loc) · 2.4 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
import math
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class Planet:
def __init__(self, x, y, radius, color, mass, vx=0, vy=0):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.mass = mass
self.vx = vx
self.vy = vy
self.orbit = [(x, y)]
def update_position(planet, dt):
planet.x += planet.vx * dt
planet.y += planet.vy * dt
def update_velocity(planet, force, dt):
ax = force[0] / planet.mass
ay = force[1] / planet.mass
planet.vx += ax * dt
planet.vy += ay * dt
def gravitational_force(planet1, planet2):
G = 1.0
dx = planet2.x - planet1.x
dy = planet2.y - planet1.y
distance_squared = dx**2 + dy**2
distance = math.sqrt(distance_squared)
force_magnitude = G * planet1.mass * planet2.mass / distance_squared
force_x = force_magnitude * dx / distance
force_y = force_magnitude * dy / distance
return (force_x, force_y)
def simulate(planets, dt):
for planet in planets:
net_force = [0, 0]
for other_planet in planets:
if planet != other_planet:
force = gravitational_force(planet, other_planet)
net_force[0] += force[0]
net_force[1] += force[1]
update_velocity(planet, net_force, dt)
for planet in planets:
update_position(planet, dt)
planet.orbit.append((planet.x, planet.y))
def animate(frame):
global planets
dt = 0.01
simulate(planets, dt)
ax.clear()
# Agregar líneas de ejes cartesianos
ax.axhline(0, color='black',linewidth=0.5)
ax.axvline(0, color='black',linewidth=0.5)
for planet in planets:
ax.scatter(planet.x, planet.y, color=planet.color, s=100, label=f'{planet.color} Planet')
updated_points = list(zip(*planet.orbit))
ax.plot(updated_points[0], updated_points[1], color=planet.color, linewidth=2)
# Crear instancias de Planet con coordenadas y velocidades iniciales
v = 1
L = 1
planet_A = Planet(-L/2, 0, 0.1, 'red', 2, v, 0)
planet_B = Planet(L/2, 0, 0.1, 'green', 2, -v / 2, v * math.sqrt(3) / 2)
planet_C = Planet(0, L * math.sqrt(3) / 2, 0.1, 'blue', 1, -v / 2, -v * math.sqrt(3) / 2)
planets = [planet_A, planet_B, planet_C]
# Configurar la animación
fig, ax = plt.subplots()
ani = FuncAnimation(fig, animate, frames=range(100), interval=50)
# Mostrar la animación
plt.show()