A Monte Carlo diffusion model moves a very large number of particles around a rectangular box, so every particle object should be as small as possible, and a typo such as p.vY = 0 must fail loudly rather than quietly create a new attribute.
Write a class Particle with exactly the four fields x, y, vx and vy, declared with __slots__, so that its objects have no __dict__ and assigning any other attribute raises AttributeError:
Particle(x, y, vx, vy)stores the position and velocity.step(dt, width, height)moves the particle byvx * dtandvy * dtinside the box0 <= x <= width,0 <= y <= height. A particle that ends up beyond a wall is reflected: past the left wall,xbecomes-x; past the right wall,xbecomes2 * width - x; and the matching velocity changes sign. The same holds forywith the bottom and top walls. (A step never crosses more than one wall per direction.)energy()returns the kinetic energy(vx ** 2 + vy ** 2) / 2.
Setup helpers you can use with Run: cloud(n, seed) makes particles, simulate(n, steps, seed, dt=0.05) runs a cloud and returns the mean position, the total energy and how many particles are in the left half, fixed_fields() checks the slots, and one_bounce() steps particles next to each wall.
Examples
Input: fixed_fields()
Output: (["vx", "vy", "x", "y"], False, "AttributeError", None, 0.0)
Input: one_bounce()[:2]
Output: [(0.3, 5.0, 4.0, 0.0), (9.7, 5.1, -4.0, 1.0)]
Constraints
- Up to 20,000 particles and 200,000 particle steps per test.
- Floats are compared with a tolerance of
1e-6.
Goals
- Declare a class's fields with `__slots__` so its objects have no `__dict__`
- See how slots turn a misspelt attribute into an error instead of a silent new attribute
- Write the small methods of a simulation class that will have very many instances