Reputation: 314
I know that the answer should be around 60% of my coordinates lie within this but im only getting about 20%
import random
import pylab
import numpy
pylab.close("all") #all import statements
x = [(random.randint(0,100)) for i in range(3000)] #creating list of x coordinates
y = [(random.randint(0,100)) for j in range(3000)] #creating list of y coordinates
array=zip(x,y) #creating an array by combining the x and y coordinates
counter = 0
for i, j in array:
if 35**2 <= (i**2+j**2) <= 65**2:
counter+= 1
print counter
Can anyone tell me what im doing wrong?
Upvotes: 0
Views: 197
Reputation: 97291
You can visualize this by pylab.imshow()
:
import numpy as np
import pylab as pl
y, x = np.mgrid[:100, :100]
d = x**2 + y**2
mask = (35**2 <= d) & (d <= 65**2)
pl.imshow(mask, origin="lower")
output:
Upvotes: 1
Reputation: 1024
Your area is 10000, in the first quadrant. You're looking at a sample with an area of
pi(65**2 - 35**2)/4
which is 2356 ... or 23.56% of the total area. So, you are getting the right answer.
BTW, your code does not need those pylab and numpy imports.
Upvotes: 2
Reputation: 365747
The problem is this line:
if 35**2 <= (i**2+j**2) <= 65**2:
This is checking whether the coordinates are between a circle of radius 35 centered at the origin, and a circle of radius 65 centered at the origin.
But since the coordinates you're testing are always in the positive-positive quadrant, only 1/4th as many will fall within the circles as you're expecting.
The simplest fix is to change the randint
calls to use (-50, 50)
instead of (0, 100)
.
Upvotes: 3
Reputation: 16503
Nope, you should be getting less than 30%. You are only filling the first quadrant!
Here's a plot:
Upvotes: 0