Python Simulations – How to Perform Monte Carlo Simulations

simulations

I wrote a few lines of code below in python.
My intentions are to generate 1000 different values of 'φ' and 'Λ' and in each case it should choose a new value of 'a' from a random range (0,1).

Then convert the values "φ" and "Λ" from cylindrical coordinates to cartesian coordinates and show the plot in the graph.

How do I generate different values of "φ" and "Λ" in this case? And I tried to convert to Cartesian but it rather shows an empty plot.
Please what do I need to do at this point in order to arrive at my results.

I sincerely appreciate your past contributions and I look forward to your help, thanks.

# import the necessary libraries
import math
import random
from math import pi

N = 1000

for num in range(N):
    a = random.uniform(0,1)
# I am using these symbols for: λ - lambda null, Λ - mean free path, φ = angle
λ = -1
φ = 2*pi*a 
Λ = λ*math.log(a) 

x = Λ*math.cos(φ) 
y = Λ*math.sin(φ)
plt.plot(x,y)
plt.show()

Best Answer

Are you sure your transformation is correct? You are using the single random variable $a$ to generate points $\phi,\,\lambda$, which means that you are tracing a path along a log-polar coordinate system (not 2D cylindrical, as you are using $\log(a)$ instead of $\sqrt{a}$). For instance, running JG's code (but using scatter() instead of plot()) I get,

enter image description here

Which seems wrong to me, as you are doing a transformation $\mathbb{R}^1\to\mathbb{R}^2$. I would think you need a transformation of $\mathbb{R}^2\to\mathbb{R}^2$ in order to plot a randomly/uniformly distributed series of points on the domain. This would be done by using two arrays of random values,

import matplotlib.pyplot as plt
import numpy as np

N = 1000
a = np.random.uniform(0, 1, size=N)
b = np.random.uniform(-1, 1, size=N)
lam = -np.log(a)
phi = np.arccos(b)
plt.scatter(lam * np.cos(phi), lam * np.sin(phi))
plt.plot()

which gives a plot more like,

enter image description here

Note that using $\phi=\cos^{-1}(x)$ for $x\in\operatorname{Uniform}(-1,1)$ is for removing biases from sampling $\operatorname{Uniform}(0,\,2\pi)$ (cf. this site, among others for sampling the hemisphere).