%pylab inline
print random.rand(10)
print random.rand(3, 4)
from mystery import mysteryf
# Testing it works
mysteryf(10)
The mysteryf function can be called directly on an array.
print mysteryf(arange(5))
theta = linspace(0, 2*pi, 400)
r = 2 + cos(7*theta)
polar(theta, r)
The functions sum, mean, min and max can all be called on one-dimensional arrays.
a = arange(10)
print a
print "Sum =", sum(a)
print "Mean =", mean(a)
print "Min =", min(a)
print "Max =", max(a)
The same can be done for higher-dimensional arrays, although we now have to use amin and amax rather than min and max.
When these functions are called, they get applied to every element of a higher-dimensional array as if it were a one-dimensional array.
a = arange(12).reshape((3, 4))
print a
print "Sum =", sum(a)
print "Mean =", mean(a)
print "Min =", amin(a)
print "Max =", amax(a)
We can also apply these operations to a single axis (such as down a column or across a row), by using the "axis" keyword.
Using "axis=0" means that the operations are applied to the elements in a column. Using sum in this way (for example) sums the elements of each column, and stores each sum separately in the resulting 1D array.
a = arange(12).reshape((3, 4))
print a
print "Sum =", sum(a, axis=0)
print "Mean =", mean(a, axis=0)
print "Min = ", amin(a, axis=0)
print "Max =", amax(a, axis=0)
print "Array shape =", a.shape
print "Result shape =", sum(a, axis=0).shape
Note that the size of axis 0 has been lost in the result (as seen in the loss of a '3' from the shape). The original array has been "compressed" vertically along axis 0 (the columns) to create the result.
If instead we wanted to apply an operation to the elements of a row, we would use "axis=1" instead. The original array is then "compressed" horizontally along axis 1 (the rows) to create the result.
a = arange(12).reshape((3, 4))
print a
print "Sum =", sum(a, axis=1)
print "Mean =", mean(a, axis=1)
print "Min = ", amin(a, axis=1)
print "Max =", amax(a, axis=1)
print "Array shape =", a.shape
print "Result shape =", sum(a, axis=1).shape
We've seen that a histogram of the output of random.rand shows an approximately uniform distribution.
What does the distribution of the sum of M random variables look like, for M = 2, 3, 4, ...?
npts = 100000
M = 2
a = random.rand(npts, M)
b = sum(a, axis=1)
hist(b, bins=50, normed=True)
xlabel('Sum')