Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place. Commercial Alternative to JupyterHub.
Math 152: Intro to Mathematical Software
2017-03-01
Kiran Kedlaya; University of California, San Diego
adapted from lectures by William Stein, University of Washington
** Lecture 21: Numpy Arrays (vs Sage Matrices) **
Peer review due Thursday 8pm.
Basic Numpy Tutorial
1. Making numpy arrays
Challenge 1:
Make a numpy ndarray
a
witha.shape==(4,)
Make a numpy ndarray
a
witha.shape==(2,3,4)
Make a numpy ndarray
a
witha.ndim==4
Make a numpy ndarray
a
witha.dtype
notdtype('int64')
Make a numpy ndarray
a
with itemsize 0
2. More about making arrays
Explicitly specifying the data type at creation time:
The following is an example of a "vectorized operation", where we apply a function to an array, which applies that function componentwise.
**Challenge 2: **
Make a numpy array with 10 equally spaced values between 0 and 1.
Use
%timeit
to see how longnp.sin(...)
takes when applied to a numpy array v with one million entries in it. Compare that to the time of doingnp.array([np.sin(x) for x in v])
andnp.array([math.sin(x) for x in v])
. Do you see the value of vectorization?Does
np.sin(a)
work if a is an array with shape (2,2)?
3. Numpy arrays "do not respect math"...
... in the same sense that some people do not respect wood...
This is just an arbitrary choice, made differently by mathematicians and engineers, so you have to be aware of it.
Challenge 3: Strangely, I don't know how to:
compute Sage's matrix exponential exp(b) using numpy
do numpy's componentwise matrix multiplication
a*b
using Sage!
And William doesn't seem to either... If anybody figures it out, let us know.
4. Binary Operations
Another major philosophical difference betweeen Sage and Numpy is that if you do a binary operation involving numpy arrays with different precision, the result has the higher precision, whereas in Sage, the result has the lower precision! Exactly the opposite choice.
(For the record, Magma does the same thing as Sage.)
5. Methods of numpy arrays
Challenge 5:
How does the speed of Numpy's
np.arange(1000000).sum()
compare to Python'ssum(range(1000000))
?How does the speed of Numpy's standard deviation (so
std
) compare to that of pandas std on a Data frame with input range(1000000)?
Heh, look up at the actual OUTPUT of the above two .std() functions -- they are completely different after the decimal point.
Caveat emptor!
6. Indexing and slicing
I hope you start to feel the power...
All this amazing slicing and dicing, and getting references into nd arrays... works on -dimensional arrays of data.