Search code examples
pythonmontecarlo

Particle hitting a wall. Monte Carlo Simulation


I've been instructed to make a function that returns a position for a given number of particles. It is a random 1D motion with the particles at the center of the Line X=0, the line is 40mm long. I am having issues coding my function so that particles reflect at the edge of the line.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import random as rd
import math as m



Box_width=20 
dx=1
No_p_motions=1000

def particle_motion_1D(n):
    x=0
    for i in range(n):
        New_x=rd.choice([(dx),(-dx)])
        x=x+New_x
    while True:
        x=x+New_x
        if x < -20:
            x = x + dx
        elsif x > 20:
            x = x -dx
    return(x)

 

for i in range(20):
    P_steps = particle_motion_1D(100)
    print(P_steps)

Solution

  • in addition to the answers on syntax above, you do not need the while loop (and the x-assignment). Also, in your limit checks you should not just increment/decrement by dx (it might move the particles outside of the limits as you would need to check the sign of the step dx) but set it to the respective limit:

    import matplotlib
    import matplotlib.pyplot as plt
    import numpy as np
    import random as rd
    import math as m
    
    Box_width = 20 
    dx = 1
    No_p_motions = 100
    
    def particle_motion_1D(n, bwidth):
        x = 0  
        for i in range(n):
            New_x = rd.choice([dx, -dx])
    #        x = x + New_x # repeated below
    #    while True: # not needed, inside the for-loop which runs over desired steps
            x = x + New_x
            if x < -bwidth: # outside lower box limit
                x = -bwidth
            elif x > bwidth: # outside upper box limit
                x = bwidth
        return(x)
    
    for i in range(20):
        P_steps = particle_motion_1D(No_p_motions, Box_width)
        print(P_steps)
    

    this produces

    4
    -6
    2
    0
    -4
    6
    -17
    6
    -6
    6
    -4
    -19
    4
    -12
    -2
    -2
    -6
    6
    -2
    -16
    

    This particle is now "well behaved" inside the limits.