Chapter 1: Computing with Python
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).
Interpreter¶
%%writefile hello.py
print("Hello from Python!")Overwriting hello.py
!python hello.pyHello from Python!
!python --versionPython 3.14.2
Input and output caching¶
(restart the kernel for the same output and cell numbers)
3 * 391 + 231 + 2;x = 1x = 2
x2Documentation¶
import os# try os.w<TAB>import mathmath.cos?Signature: math.cos(x, /)
Docstring: Return the cosine of x (measured in radians).
Type: builtin_function_or_methodInteraction with System Shell¶
!touch file1.py file2.py file3.py!ls file*file1.py file2.py file3.py
files = !ls file*len(files)3files['file1.py', 'file2.py', 'file3.py']file = "file1.py"!ls -l $file-rw-r--r-- 1 carlosal1015 carlosal1015 0 Jan 23 13:37 file1.py
Running scripts from the IPython console¶
%%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]Debugger¶
fib(1)[1]# %debugTiming and profiling code¶
%timeit fib(100)3.82 μs ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
result = %time fib(100)CPU times: user 10 μs, sys: 0 ns, total: 10 μs
Wall time: 13.1 μs
len(result)100import 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) Fetching long content....
Jupyter notebook¶
from IPython.display import HTML, Image, Math, displayImage(url="http://python.org/images/python-logo.gif")Loading...
import matplotlib
import numpy
import scipy
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>" % rowss'<table> <tr><th>Library</th><th>Version</th> </tr> <tr> <td>numpy</td> <td>2.4.1</td> </tr>\n<tr> <td>matplotlib</td> <td>3.10.8</td> </tr>\n<tr> <td>scipy</td> <td>1.17.0</td> </tr></table>'HTML(s)Loading...
class HTMLDisplayer(object):
def __init__(self, code):
self.code = code
def _repr_html_(self):
return self.codeHTMLDisplayer(s)Loading...
Math(r"\hat{H} = -\frac{1}{2}\epsilon \hat{\sigma}_z-\frac{1}{2}\delta \hat{\sigma}_x")Loading...
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)Loading...
import matplotlib.pyplot as plt
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 figimport ipywidgets as widgets
from ipywidgets import interactinteract(f, mu=widgets.FloatSlider(min=1.0, max=20.0, step=1.0));Loading...
Jupyter nbconvert¶
!jupyter nbconvert --to html ch01-code-listing.ipynb[NbConvertApp] Converting notebook ch01-code-listing.ipynb to html
[NbConvertApp] Writing 315660 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 42317 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 48819 bytes to ch01-code-listing.pdf
!jupyter nbconvert ch01-code-listing.ipynb --to python[NbConvertApp] Converting notebook ch01-code-listing.ipynb to python
[NbConvertApp] Writing 4532 bytes to ch01-code-listing.py
- Johansson, R. (2024). Numerical Python: Scientific Computing and Data Science Applications with Numpy, SciPy and Matplotlib. Apress. 10.1007/979-8-8688-0413-7