MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / BodySystem

Class BodySystem

physics/n_body_simulation.py:112–182  ·  view source on GitHub ↗

This class is used to hold the bodies, the gravitation constant, the time factor and the softening factor. The time factor is used to control the speed of the simulation. The softening factor is used for softening, a numerical trick for N-body simulations to prevent numerical di

Source from the content-addressed store, hash-verified

110
111
112class BodySystem:
113 """
114 This class is used to hold the bodies, the gravitation constant, the time
115 factor and the softening factor. The time factor is used to control the speed
116 of the simulation. The softening factor is used for softening, a numerical
117 trick for N-body simulations to prevent numerical divergences when two bodies
118 get too close to each other.
119 """
120
121 def __init__(
122 self,
123 bodies: list[Body],
124 gravitation_constant: float = 1.0,
125 time_factor: float = 1.0,
126 softening_factor: float = 0.0,
127 ) -> None:
128 self.bodies = bodies
129 self.gravitation_constant = gravitation_constant
130 self.time_factor = time_factor
131 self.softening_factor = softening_factor
132
133 def __len__(self) -> int:
134 return len(self.bodies)
135
136 def update_system(self, delta_time: float) -> None:
137 """
138 For each body, loop through all other bodies to calculate the total
139 force they exert on it. Use that force to update the body's velocity.
140
141 >>> body_system_1 = BodySystem([Body(0,0,0,0), Body(10,0,0,0)])
142 >>> len(body_system_1)
143 2
144 >>> body_system_1.update_system(1)
145 >>> body_system_1.bodies[0].position
146 (0.01, 0.0)
147 >>> body_system_1.bodies[0].velocity
148 (0.01, 0.0)
149
150 >>> body_system_2 = BodySystem([Body(-10,0,0,0), Body(10,0,0,0, mass=4)], 1, 10)
151 >>> body_system_2.update_system(1)
152 >>> body_system_2.bodies[0].position
153 (-9.0, 0.0)
154 >>> body_system_2.bodies[0].velocity
155 (0.1, 0.0)
156 """
157 for body1 in self.bodies:
158 force_x = 0.0
159 force_y = 0.0
160 for body2 in self.bodies:
161 if body1 != body2:
162 dif_x = body2.position_x - body1.position_x
163 dif_y = body2.position_y - body1.position_y
164
165 # Calculation of the distance using Pythagoras's theorem
166 # Extra factor due to the softening technique
167 distance = (dif_x**2 + dif_y**2 + self.softening_factor) ** (1 / 2)
168
169 # Newton's law of universal gravitation.

Callers 3

example_1Function · 0.85
example_2Function · 0.85
example_3Function · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected