Basic Python Programming Help Needed Involving Arrays And Random Locations
Solution 1:
You can skip actually generating the array and go directly to the frequency calculation:
First of all, it should be noted that since both the x and y coordinates are completely random:
We have the rule:
P(A or B) = P(A) + P(B) - P(A and B)
So we can say that
P(X or Y within 15) = P(X within 15) + P(Y within 15) - P(X and Y within 15)
Since it's implied that X and Y are uniformly random from 0 to 99
(or from 1 to 100
), we can assume that
P(X within 15) = P(Y within 15)
So the whole thing becomes
P(X or Y within 15) = 2P(X within 15) - P(X within 15)^2
Now, we just need to calculate P(X within 15)
. Observe that X can only take integer values, so the function f(x) = |X - 49.5| - 35
will be greater than zero for x = 0..14
and x = 85..99
. (We're indexing from zero, but it's the equivalent to going from 1...100
).
So, the code:
from random import randrange
N = 3000
P_x_within_15 = sum(abs(randrange(100) - 49.5) - 35 > 0 for _ in range(N)) / float(N)
print "Frequency of X or Y within 15 pixels of edge:",
print 2 * P_x_within_15 - P_x_within_15 ** 2
As you may have noticed, we skipped actually creating an array, and just added up the boolean (True/False with True = 1, False = 0) results of the random numbers as they were generated.
EDIT - Actually creating an array
To create an array of random coordinates for a 100 x 100 matrix:
Using numpy
the code would be:
from random import randrange
N = 3000
coords_array = array([randrange(100) for _ in range(2 * N)]).reshape(N, 2)
Using pure python, it would be:
from random import randrange
N = 3000
coords_list = [(randrange(100), randrange(100)) for _ in range(N)]
A couple things to note here:
In python, indices are sequenced from zero.
randrange(100)
will give you a number between 0 and 99, inclusive.N
is simply the number of coordinates we wish to generateTerminology point: In python, the data structures represented by square brackets are
list
s, not arrays (even though they are equivalent to arrays in other programming languages). In your code abovearray1
is a pythonlist
, not anarray
(which is a different data structure). Counterpoint:numpy
however, extensively uses arrays. In your code, when you doarray(array1)
, you are, in fact, creating anumpy
array.The stuff between the square brackets is called a list comprehension. It is semantically equivalent to:
coords_list = []
for _ in range(N):
coords_list.append((randrange(100), randrange(100)))
Post a Comment for "Basic Python Programming Help Needed Involving Arrays And Random Locations"