2025-plovdiv-scientific-pat.../class_materials/exercises/particle_update_position.ipynb
2025-09-25 11:03:48 +03:00

3.4 KiB

Exercise: Add the function update_position to the Particle class

  • Make the function update_position into a method of the class Particle
  • Where do the position position of the particle belong? Modify the class constructor if necessary
  • Once it is done, create a particle with mass 2.1 with velocity 0.8 at position 8.2 . Update the position with dt=0.1 and print out the new location.
In [1]:
def update_position(velocity, position, dt):
    return position + velocity * dt
In [6]:
class Particle:
    def __init__(self, mass=1, velocity=0., position=0.):
        self.mass = mass
        self.velocity = velocity
        self.position = position

    def momentum(self):
        return self.mass * self.velocity

    def update_position(self, dt):
        new_position = self.position + dt * self.velocity
        self.position = new_position
        return
In [7]:
particle = Particle(mass=2.1, velocity=0.8, position=0.)
print(particle.momentum())
print(particle.position)
1.6800000000000002
0.0
In [8]:
particle.update_position(dt=0.1)
print(particle.position)
0.08000000000000002
In [ ]:

In [ ]: