Q:

Monte Carlo Simulation to estimating pi using circle

I have a question on the algorithm below. What confused me is why x = random.random()*2 -1 and y = random.random()*2 -1 rather than just simply x = random.random() and y = random.random()? The complete code is as following:
import random

NUMBER_OF_TRIALS= 1000000
numberOfHits = 0

for i in range(NUMBER_OF_TRIALS):
    x = random.random()*2 -1
    y = random.random()*2 -1

    if x * x + y * y <=1:
         numberOfHits +=1
pi = 4* numberOfHits / NUMBER_OF_TRIALS

print("PI is", pi)

A:

The circle in this simulation is centered at (0, 0) with a radius of 1, so
x = random.random() * 2 - 1
y = random.random() * 2 - 1

will make the range for each -1 to 1.

A:

The interesting thing about this question is that the implementation works just as well, and gives you the same expected answer whether you use random.random() or random.random()*2-1...  so the reason why the author chose to use random.random()*2-1 has nothing to do with what the program does.
The author of this code understands the algorithm as follows:

Imagine a circle inscribe in a square.  Use the unit circle because it's simplest
Choose random points within the square, and see how many are also inside the circle
The circle has area pi and the square has area 4, so the proportion of points that fall in the circle will approach pi/4.  Calculate the measured ratio and solve for pi.

Now, the square in which the unit circle is inscribed goes from (-1,-1) to (1,1).  Since random() only gives you a number in [0,1), it needs to be multiplied by two and shifted to select a random number in [-1,1), which chooses random points within the square.
If the author had used random(), then he would be selecting point within the first quadrant only.  All the quadrants look exactly the same, so the ratio of hits to misses would be the same and the program would still work just fine, but then the program would not be implementing the above-described procedure, and would be more difficult to understand.
One of the most important properties of good code is that it clearly communicates the author's intent.

