Generating Random Points and Estimating \( \pi \)
inside = sum(u(-1, 1, n)**2 + u(-1, 1, n)**2 + u(-1, 1, n)**2 <= 1)
This line performs:
- u(-1, 1, n) generates n random numbers uniformly distributed between -1 and 1. The expression u(-1, 1, n)**2 computes the square of each of these random numbers.
- The process is repeated three times to generate three sets of random numbers, which represent the coordinates \( (x, y, z) \) in a 3D space.
- The code calculates the condition:
$$ x^2 + y^2 + z^2 \leq 1 $$
This condition checks whether each of the generated points lies inside a unit sphere (which is defined by the equation \( x^2 + y^2 + z^2 \leq 1 \)).
- sum(...) counts how many of these points fall inside the unit sphere. The result is stored in the variable inside.
Estimating \( \pi \):
pi = 6.0 * inside / n
estimation of \( \pi \) using the formula:
The volume of the unit sphere is \( \frac{4}{3}\pi \cdot1^3 \), while the volume of the cube defined by the range \( [-1, 1] \) is \( 2^3 = 8 \).
$$ \frac{V_{sphere}}{V_{cube}} = \frac{\frac{4}{3}\pi}{8}$$
$$ \pi \approx \frac{6 \cdot (\text{number of points inside the sphere})}{\text{total number of points}} $$