Robert Johansson
Source code listings for Numerical Python - Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib (ISBN 979-8-8688-0412-0).
%%writefile hello.py
print("Hello from Python!")
Overwriting hello.py
!python hello.py
Hello from Python!
!python --version
Python 3.10.12
(restart the kernel for the same output and cell numbers)
3 * 3
9
In[1]
'3 * 3'
Out[1]
9
In
['', '3 * 3', 'In[1]', 'Out[1]', 'In']
Out
{1: 9, 2: '3 * 3', 3: 9, 4: ['', '3 * 3', 'In[1]', 'Out[1]', 'In', 'Out']}
1+2
3
1+2;
x = 1
x = 2; x
2
import os
# try os.w<TAB>
import math
math.cos?
Signature: math.cos(x, /) Docstring: Return the cosine of x (measured in radians). Type: builtin_function_or_method
!touch file1.py file2.py file3.py
!ls file*
file1.py file2.py file3.py
files = !ls file*
len(files)
3
files
['file1.py', 'file2.py', 'file3.py']
file = "file1.py"
!ls -l $file
-rw-------@ 1 rob staff 0 Nov 2 17:58 file1.py
%%writefile fib.py
def fib(N):
"""
Return a list of the first N Fibonacci numbers.
"""
f0, f1 = 0, 1
f = [1] * N
for n in range(1, N):
f[n] = f0 + f1
f0, f1 = f1, f[n]
return f
print(fib(10))
Overwriting fib.py
!python fib.py
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
%run fib.py
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
fib(6)
[1, 1, 2, 3, 5, 8]
fib(1.0)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) Cell In[25], line 1 ----> 1 fib(1.0) File ~/OneDrive/Desktop/npbook-ed3/code/numerical-python-code-ed3-v2-github/fib.py:7, in fib(N) 3 """ 4 Return a list of the first N Fibonacci numbers. 5 """ 6 f0, f1 = 0, 1 ----> 7 f = [1] * N 8 for n in range(1, N): 9 f[n] = f0 + f1 TypeError: can't multiply sequence by non-int of type 'float'
%debug
> /Users/rob/OneDrive/Desktop/npbook-ed3/code/numerical-python-code-ed3-v2-github/fib.py(7)fib() 5 """ 6 f0, f1 = 0, 1 ----> 7 f = [1] * N 8 for n in range(1, N): 9 f[n] = f0 + f1
1.0
%timeit fib(100)
11.6 µs ± 532 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
result = %time fib(100)
CPU times: user 21 µs, sys: 1 µs, total: 22 µs Wall time: 24.8 µs
len(result)
100
import numpy as np
def random_walker_max_distance(M, N):
"""
Simulate N random walkers taking M steps, and return the largest distance
from the starting point achieved by any of the random walkers.
"""
trajectories = [np.random.randn(M).cumsum() for _ in range(N)]
return np.max(np.abs(trajectories))
%prun random_walker_max_distance(400, 10000)
20013 function calls in 0.335 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
10000 0.184 0.000 0.184 0.000 {method 'randn' of 'numpy.random.mtrand.RandomState' objects}
10000 0.071 0.000 0.071 0.000 {method 'cumsum' of 'numpy.ndarray' objects}
1 0.051 0.051 0.328 0.328 2615584822.py:3(random_walker_max_distance)
1 0.020 0.020 0.276 0.276 2615584822.py:8(<listcomp>)
1 0.007 0.007 0.335 0.335 <string>:1(<module>)
1 0.002 0.002 0.002 0.002 {method 'reduce' of 'numpy.ufunc' objects}
1 0.000 0.000 0.335 0.335 {built-in method builtins.exec}
1 0.000 0.000 0.002 0.002 fromnumeric.py:69(_wrapreduction)
1 0.000 0.000 0.002 0.002 <__array_function__ internals>:177(amax)
1 0.000 0.000 0.002 0.002 fromnumeric.py:2675(amax)
1 0.000 0.000 0.002 0.002 {built-in method numpy.core._multiarray_umath.implement_array_function}
1 0.000 0.000 0.000 0.000 fromnumeric.py:70(<dictcomp>)
1 0.000 0.000 0.000 0.000 fromnumeric.py:2670(_amax_dispatcher)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
1 0.000 0.000 0.000 0.000 {method 'items' of 'dict' objects}
from IPython.display import display, Image, HTML, Math
Image(url='http://python.org/images/python-logo.gif')
import scipy, numpy, matplotlib
modules = [numpy, matplotlib, scipy]
row = "<tr> <td>%s</td> <td>%s</td> </tr>"
rows = "\n".join([row % (module.__name__, module.__version__) for module in modules])
s = "<table> <tr><th>Library</th><th>Version</th> </tr> %s</table>" % rows
s
'<table> <tr><th>Library</th><th>Version</th> </tr> <tr> <td>numpy</td> <td>1.22.3</td> </tr>\n<tr> <td>matplotlib</td> <td>3.7.1</td> </tr>\n<tr> <td>scipy</td> <td>1.7.3</td> </tr></table>'
HTML(s)
| Library | Version |
|---|---|
| numpy | 1.22.3 |
| matplotlib | 3.7.1 |
| scipy | 1.7.3 |
class HTMLDisplayer(object):
def __init__(self, code):
self.code = code
def _repr_html_(self):
return self.code
HTMLDisplayer(s)
| Library | Version |
|---|---|
| numpy | 1.22.3 |
| matplotlib | 3.7.1 |
| scipy | 1.7.3 |
Math(r'\hat{H} = -\frac{1}{2}\epsilon \hat{\sigma}_z-\frac{1}{2}\delta \hat{\sigma}_x')
class QubitHamiltonian(object):
def __init__(self, epsilon, delta):
self.epsilon = epsilon
self.delta = delta
def _repr_latex_(self):
return "$\hat{H} = -%.2f\hat{\sigma}_z-%.2f\hat{\sigma}_x$" % \
(self.epsilon/2, self.delta/2)
QubitHamiltonian(0.5, 0.25)
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
def f(mu):
X = stats.norm(loc=mu, scale=np.sqrt(mu))
N = stats.poisson(mu)
x = np.linspace(0, X.ppf(0.999))
n = np.arange(0, x[-1])
fig, ax = plt.subplots()
ax.plot(x, X.pdf(x), color='black', lw=2, label="Normal($\mu=%d, \sigma^2=%d$)" % (mu, mu))
ax.bar(n, N.pmf(n), align='edge', label=r"Poisson($\lambda=%d$)" % mu)
ax.set_ylim(0, X.pdf(x).max() * 1.25)
ax.legend(loc=2, ncol=2)
plt.close(fig)
return fig
from ipywidgets import interact
import ipywidgets as widgets
interact(f, mu=widgets.FloatSlider(min=1.0, max=20.0, step=1.0));
interactive(children=(FloatSlider(value=1.0, description='mu', max=20.0, min=1.0, step=1.0), Output()), _dom_c…
!jupyter nbconvert --to html ch01-code-listing.ipynb
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to html [NbConvertApp] Writing 649717 bytes to ch01-code-listing.html
!jupyter nbconvert --to pdf ch01-code-listing.ipynb
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to pdf [NbConvertApp] Writing 57494 bytes to notebook.tex [NbConvertApp] Building PDF [NbConvertApp] Running xelatex 3 times: ['xelatex', 'notebook.tex', '-quiet'] [NbConvertApp] Running bibtex 1 time: ['bibtex', 'notebook'] [NbConvertApp] WARNING | bibtex had problems, most likely because there were no citations [NbConvertApp] PDF successfully created [NbConvertApp] Writing 66341 bytes to ch01-code-listing.pdf
%%writefile custom_template.tplx
((*- extends 'article.tplx' -*))
((* block title *)) \title{Document title} ((* endblock title *))
((* block author *)) \author{Author's Name} ((* endblock author *))
Overwriting custom_template.tplx
!jupyter nbconvert ch01-code-listing.ipynb --to pdf --template custom_template.tplx
!jupyter nbconvert ch01-code-listing.ipynb --to python
[NbConvertApp] Converting notebook ch01-code-listing.ipynb to python [NbConvertApp] Writing 5152 bytes to ch01-code-listing.py
%reload_ext version_information
%version_information numpy
| Software | Version |
|---|---|
| Python | 3.10.12 64bit [Clang 14.0.6 ] |
| IPython | 8.12.0 |
| OS | macOS 10.15.7 x86\_64 i386 64bit |
| numpy | 1.22.3 |
| Sat Nov 02 17:59:59 2024 JST | |