Files
FYS-STK4155/doc/src/LectureNotes/_build/html/testbook/chapter2.html
T
2020-12-23 23:05:47 +01:00

1915 lines
129 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities &#8212; Applied Machine Learning and Data Analysis</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
<link href="../_static/css/index.css" rel="stylesheet">
<link rel="stylesheet" href="../_static/sphinx-book-theme.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<link rel="stylesheet" type="text/css" href="../_static/togglebutton.css" />
<link rel="stylesheet" type="text/css" href="../_static/copybutton.css" />
<link rel="stylesheet" type="text/css" href="../_static/mystnb.css" />
<link rel="stylesheet" type="text/css" href="../_static/sphinx-thebe.css" />
<link rel="stylesheet" type="text/css" href="../_static/panels-main.c949a650a448cc0ae9fd3441c0e17fb0.css" />
<link rel="stylesheet" type="text/css" href="../_static/panels-variables.06eb56fa6e07937060861dad626602ad.css" />
<script id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
<script src="../_static/jquery.js"></script>
<script src="../_static/underscore.js"></script>
<script src="../_static/doctools.js"></script>
<script src="../_static/language_data.js"></script>
<script src="../_static/togglebutton.js"></script>
<script src="../_static/clipboard.min.js"></script>
<script src="../_static/copybutton.js"></script>
<script src="../_static/sphinx-book-theme.js"></script>
<script >var togglebuttonSelector = '.toggle, .admonition.dropdown, .tag_hide_input div.cell_input, .tag_hide-input div.cell_input, .tag_hide_output div.cell_output, .tag_hide-output div.cell_output, .tag_hide_cell.cell, .tag_hide-cell.cell';</script>
<script async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.7/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
<script type="text/x-mathjax-config">MathJax.Hub.Config({"tex2jax": {"inlineMath": [["\\(", "\\)"]], "displayMath": [["\\[", "\\]"]], "processRefs": false, "processEnvironments": false}})</script>
<script async="async" src="https://unpkg.com/thebelab@latest/lib/index.js"></script>
<script >
const thebe_selector = ".thebe"
const thebe_selector_input = "pre"
const thebe_selector_output = ".output"
</script>
<script async="async" src="../_static/sphinx-thebe.js"></script>
<link rel="index" title="Index" href="../genindex.html" />
<link rel="search" title="Search" href="../search.html" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="docsearch:language" content="en">
</head>
<body data-spy="scroll" data-target="#bd-toc-nav" data-offset="80">
<div class="container-xl">
<div class="row">
<div class="col-12 col-md-3 bd-sidebar site-navigation show" id="site-navigation">
<div class="navbar-brand-box">
<a class="navbar-brand text-wrap" href="../index.html">
<img src="../_static/Picture.png" class="logo" alt="logo">
<h1 class="site-logo" id="site-title">Applied Machine Learning and Data Analysis</h1>
</a>
</div>
<form class="bd-search d-flex align-items-center" action="../search.html" method="get">
<i class="icon fas fa-search"></i>
<input type="search" class="form-control" name="q" id="search-input" placeholder="Search this book..." aria-label="Search this book..." autocomplete="off" >
</form>
<nav class="bd-links" id="bd-docs-nav" aria-label="Main navigation">
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="../chapter1.html">
Introduction to Applied Data Analysis and Machine Learning
</a>
</li>
</ul>
<p class="caption">
<span class="caption-text">
Supervised Learning
</span>
</p>
<ul class="nav sidenav_l1">
<li class="toctree-l1">
<a class="reference internal" href="../chapter2.html">
1. Elements of Probability Theory and Statistical Data Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter3.html">
2. Getting started, our first data and Machine Learning encounters
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter4.html">
3. Linear Regression and more Advanced Regression Analysis
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter5.html">
4. Logistic Regression
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter6.html">
5. Neural networks, from the simple perceptron to deep learning
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter7.html">
6. Support Vector Machines, overarching aims
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter8.html">
7. Dimensionality Reduction
</a>
</li>
<li class="toctree-l1">
<a class="reference internal" href="../chapter9.html">
8. Convolutional Neural Networks
</a>
</li>
</ul>
</nav>
<!-- To handle the deprecated key -->
<div class="navbar_extra_footer">
Powered by <a href="https://jupyterbook.org">Jupyter Book</a>
</div>
</div>
<main class="col py-md-3 pl-md-4 bd-content overflow-auto" role="main">
<div class="row topbar fixed-top container-xl">
<div class="col-12 col-md-3 bd-topbar-whitespace site-navigation show">
</div>
<div class="col pl-2 topbar-main">
<button id="navbar-toggler" class="navbar-toggler ml-0" type="button" data-toggle="collapse"
data-toggle="tooltip" data-placement="bottom" data-target=".site-navigation" aria-controls="navbar-menu"
aria-expanded="true" aria-label="Toggle navigation" aria-controls="site-navigation"
title="Toggle navigation" data-toggle="tooltip" data-placement="left">
<i class="fas fa-bars"></i>
<i class="fas fa-arrow-left"></i>
<i class="fas fa-arrow-up"></i>
</button>
<div class="dropdown-buttons-trigger">
<button id="dropdown-buttons-trigger" class="btn btn-secondary topbarbtn" aria-label="Download this page"><i
class="fas fa-download"></i></button>
<div class="dropdown-buttons">
<!-- ipynb file if we had a myst markdown file -->
<!-- Download raw file -->
<a class="dropdown-buttons" href="../_sources/testbook/chapter2.ipynb"><button type="button"
class="btn btn-secondary topbarbtn" title="Download source file" data-toggle="tooltip"
data-placement="left">.ipynb</button></a>
<!-- Download PDF via print -->
<button type="button" id="download-print" class="btn btn-secondary topbarbtn" title="Print to PDF"
onClick="window.print()" data-toggle="tooltip" data-placement="left">.pdf</button>
</div>
</div>
<!-- Source interaction buttons -->
<!-- Full screen (wrap in <a> to have style consistency -->
<a class="full-screen-button"><button type="button" class="btn btn-secondary topbarbtn" data-toggle="tooltip"
data-placement="bottom" onclick="toggleFullScreen()" title="Fullscreen mode"><i
class="fas fa-expand"></i></button></a>
<!-- Launch buttons -->
</div>
<!-- Table of contents -->
<div class="d-none d-md-block col-md-2 bd-toc show">
<div class="tocsection onthispage pt-5 pb-3">
<i class="fas fa-list"></i> Contents
</div>
<nav id="bd-toc-nav">
<ul class="nav section-nav flex-column">
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#dimension-units-and-labels">
Dimension, units and labels
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#elements-of-vector-algebra">
Elements of Vector Algebra
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#falling-baseball-in-one-dimension">
Falling baseball in one dimension
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#our-python-encounter">
Our Python Encounter
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#average-quantities">
Average quantities
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#compact-equations">
Compact equations
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#a-differential-equation">
A differential equation
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#integrating-our-equations">
Integrating our equations
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#constant-acceleration-case-the-velocity">
Constant acceleration case, the velocity
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#computing-the-averages">
Computing the averages
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#including-air-resistance-in-our-model">
Including Air Resistance in our model
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#analytical-solutions">
Analytical solutions
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#finding-the-final-height">
Finding the final height
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#our-first-attempt-at-solving-differential-equations">
Our first attempt at solving differential equations
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#discretizing-our-equations">
Discretizing our equations
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#code-for-implementing-euler-s-method">
Code for implementing Eulers method
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#simple-extension-the-euler-cromer-method">
Simple extension, the Euler-Cromer method
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#python-practicalities-software-and-needed-installations">
Python practicalities, Software and needed installations
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#python-installers">
Python installers
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#useful-python-libraries">
Useful Python libraries
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#numpy-examples-and-important-matrix-and-vector-handling-packages">
Numpy examples and Important Matrix and vector handling packages
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#basic-matrix-features">
Basic Matrix Features
</a>
<ul class="nav section-nav flex-column">
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#some-famous-matrices">
Some famous Matrices
</a>
</li>
<li class="toc-h3 nav-item toc-entry">
<a class="reference internal nav-link" href="#more-basic-matrix-features">
More Basic Matrix Features
</a>
</li>
</ul>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#numpy-and-arrays">
Numpy and arrays
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#matrices-in-python">
Matrices in Python
</a>
</li>
<li class="toc-h2 nav-item toc-entry">
<a class="reference internal nav-link" href="#meet-the-pandas">
Meet the Pandas
</a>
</li>
</ul>
</nav>
</div>
</div>
<div id="main-content" class="row">
<div class="col-12 col-md-9 pl-md-3 pr-md-0">
<div>
<div class="section" id="space-time-motion-reference-frames-and-reminder-on-vectors-and-other-mathematical-quantities">
<h1>Space, Time, Motion, Reference Frames and Reminder on vectors and other mathematical quantities<a class="headerlink" href="#space-time-motion-reference-frames-and-reminder-on-vectors-and-other-mathematical-quantities" title="Permalink to this headline"></a></h1>
<p>Our studies will start with the motion of different types of objects
such as a falling ball, a runner, a bicycle etc etc. It means that an
objects position in space varies with time.
In order to study such systems we need to define</p>
<ul class="simple">
<li><p>choice of origin</p></li>
<li><p>choice of the direction of the axes</p></li>
<li><p>choice of positive direction (left-handed or right-handed system of reference)</p></li>
<li><p>choice of units and dimensions</p></li>
</ul>
<p>These choices lead to some important questions such as</p>
<ul class="simple">
<li><p>is the physics of a system independent of the origin of the axes?</p></li>
<li><p>is the physics independent of the directions of the axes, that is are there privileged axes?</p></li>
<li><p>is the physics independent of the orientation of system?</p></li>
<li><p>is the physics independent of the scale of the length?</p></li>
</ul>
<div class="section" id="dimension-units-and-labels">
<h2>Dimension, units and labels<a class="headerlink" href="#dimension-units-and-labels" title="Permalink to this headline"></a></h2>
<p>Throughout this course we will use the standardized SI units. The standard unit for length is thus one meter 1m, for mass
one kilogram 1kg, for time one second 1s, for force one Newton 1kgm/s<span class="math notranslate nohighlight">\(^2\)</span> and for energy 1 Joule 1kgm<span class="math notranslate nohighlight">\(^2\)</span>s<span class="math notranslate nohighlight">\(^{-2}\)</span>.</p>
<p>We will use the following notations for various variables (vectors are always boldfaced in these lecture notes):</p>
<ul class="simple">
<li><p>position <span class="math notranslate nohighlight">\(\boldsymbol{r}\)</span>, in one dimention we will normally just use <span class="math notranslate nohighlight">\(x\)</span>,</p></li>
<li><p>mass <span class="math notranslate nohighlight">\(m\)</span>,</p></li>
<li><p>time <span class="math notranslate nohighlight">\(t\)</span>,</p></li>
<li><p>velocity <span class="math notranslate nohighlight">\(\boldsymbol{v}\)</span> or just <span class="math notranslate nohighlight">\(v\)</span> in one dimension,</p></li>
<li><p>acceleration <span class="math notranslate nohighlight">\(\boldsymbol{a}\)</span> or just <span class="math notranslate nohighlight">\(a\)</span> in one dimension,</p></li>
<li><p>momentum <span class="math notranslate nohighlight">\(\boldsymbol{p}\)</span> or just <span class="math notranslate nohighlight">\(p\)</span> in one dimension,</p></li>
<li><p>kinetic energy <span class="math notranslate nohighlight">\(K\)</span>,</p></li>
<li><p>potential energy <span class="math notranslate nohighlight">\(V\)</span> and</p></li>
<li><p>frequency <span class="math notranslate nohighlight">\(\omega\)</span>.</p></li>
</ul>
<p>More variables will be defined as we need them.</p>
<p>It is also important to keep track of dimensionalities. Dont mix this up with a chosen unit for a given variable. We mark the dimensionality in these lectures as <span class="math notranslate nohighlight">\([a]\)</span>, where <span class="math notranslate nohighlight">\(a\)</span> is the quantity we are interested in. Thus</p>
<ul class="simple">
<li><p><span class="math notranslate nohighlight">\([\boldsymbol{r}]=\)</span> length</p></li>
<li><p><span class="math notranslate nohighlight">\([m]=\)</span> mass</p></li>
<li><p><span class="math notranslate nohighlight">\([K]=\)</span> energy</p></li>
<li><p><span class="math notranslate nohighlight">\([t]=\)</span> time</p></li>
<li><p><span class="math notranslate nohighlight">\([\boldsymbol{v}]=\)</span> length over time</p></li>
<li><p><span class="math notranslate nohighlight">\([\boldsymbol{a}]=\)</span> length over time squared</p></li>
<li><p><span class="math notranslate nohighlight">\([\boldsymbol{p}]=\)</span> mass times length over time</p></li>
<li><p><span class="math notranslate nohighlight">\([\omega]=\)</span> 1/time</p></li>
</ul>
</div>
<div class="section" id="elements-of-vector-algebra">
<h2>Elements of Vector Algebra<a class="headerlink" href="#elements-of-vector-algebra" title="Permalink to this headline"></a></h2>
<p><strong>Note</strong>: This section is under revision</p>
<p>In these lectures we will use boldfaced lower-case letters to label a vector. A vector <span class="math notranslate nohighlight">\(\boldsymbol{a}\)</span> in three dimensions is thus defined as</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{a} =(a_x,a_y, a_z),
\]</div>
<p>and using the unit vectors in a cartesian system we have</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{a} = a_x\boldsymbol{e}_x+a_y\boldsymbol{e}_y+a_z\boldsymbol{e}_z,
\]</div>
<p>where the unit vectors have magnitude <span class="math notranslate nohighlight">\(\vert\boldsymbol{e}_i\vert = 1\)</span> with <span class="math notranslate nohighlight">\(i=x,y,z\)</span>.</p>
<p>Using the fact that multiplication of reals is distributive we can show that</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{a}(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\boldsymbol{b}+\boldsymbol{a}\boldsymbol{c},
\]</div>
<p>Similarly we can also show that (using product rule for differentiating reals)</p>
<div class="math notranslate nohighlight">
\[
\frac{d}{dt}(\boldsymbol{a}\boldsymbol{b})=\boldsymbol{a}\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\frac{d\boldsymbol{a}}{dt}.
\]</div>
<p>We can repeat these operations for the cross products and show that they are distribuitive</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{a}\times(\boldsymbol{b}+\boldsymbol{c})=\boldsymbol{a}\times\boldsymbol{b}+\boldsymbol{a}\times\boldsymbol{c}.
\]</div>
<p>We have also that</p>
<div class="math notranslate nohighlight">
\[
\frac{d}{dt}(\boldsymbol{a}\times\boldsymbol{b})=\boldsymbol{a}\times\frac{d\boldsymbol{b}}{dt}+\boldsymbol{b}\times\frac{d\boldsymbol{a}}{dt}.
\]</div>
<p>The rotation of a three-dimensional vector <span class="math notranslate nohighlight">\(\boldsymbol{a}=(a_x,a_y,a_z)\)</span> in the <span class="math notranslate nohighlight">\(xy\)</span> plane around an angle <span class="math notranslate nohighlight">\(\phi\)</span> results in a new vector <span class="math notranslate nohighlight">\(\boldsymbol{b}=(b_x,b_y,b_z)\)</span>. This operation can be expressed in terms of linear algebra as a matrix (the rotation matrix) multiplied with a vector. We can write this as</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\begin{bmatrix} b_x \\ b_y \\ b_z \end{bmatrix} = \begin{bmatrix} \cos{\phi} &amp; \sin{\phi} &amp; 0 \\ -\sin{\phi} &amp; \cos{\phi} &amp; 0 \\ 0 &amp; 0 &amp; 1\end{bmatrix}\begin{bmatrix} a_x \\ a_y \\ a_z \end{bmatrix}.
\end{split}\]</div>
<p>We can write this in a more compact form as <span class="math notranslate nohighlight">\(\boldsymbol{b} = \boldsymbol{R}\boldsymbol{a}\)</span>, where the rotation matrix is defined as</p>
<div class="math notranslate nohighlight">
\[\begin{split}
\boldsymbol{R} = \begin{bmatrix} \cos{\phi} &amp; \sin{\phi} &amp; 0 \\ -\sin{\phi} &amp; \cos{\phi} &amp; 0 \\ 0 &amp; 0 &amp; 1\end{bmatrix}.
\end{split}\]</div>
</div>
<div class="section" id="falling-baseball-in-one-dimension">
<h2>Falling baseball in one dimension<a class="headerlink" href="#falling-baseball-in-one-dimension" title="Permalink to this headline"></a></h2>
<p>We anticipate the mathematical model to come and assume that we have a
model for the motion of a falling baseball without air resistance.
Our system (the baseball) is at an initial height <span class="math notranslate nohighlight">\(y_0\)</span> (which we will
specify in the program below) at the initial time <span class="math notranslate nohighlight">\(t_0=0\)</span>. In our program example here we will plot the position in steps of <span class="math notranslate nohighlight">\(\Delta t\)</span> up to a final time <span class="math notranslate nohighlight">\(t_f\)</span>.
The mathematical formula for the position <span class="math notranslate nohighlight">\(y(t)\)</span> as function of time <span class="math notranslate nohighlight">\(t\)</span> is</p>
<div class="math notranslate nohighlight">
\[
y(t) = y_0-\frac{1}{2}gt^2,
\]</div>
<p>where <span class="math notranslate nohighlight">\(g=9.80665=0.980655\times 10^1\)</span>m/s<span class="math notranslate nohighlight">\(^2\)</span> is a constant representing the standard acceleration due to gravity.
We have here adopted the conventional standard value. This does not take into account other effects, such as buoyancy or drag.
Furthermore, we stop when the ball hits the ground, which takes place at</p>
<div class="math notranslate nohighlight">
\[
y(t) = 0= y_0-\frac{1}{2}gt^2,
\]</div>
<p>which gives us a final time <span class="math notranslate nohighlight">\(t_f=\sqrt{2y_0/g}\)</span>.</p>
<p>As of now we simply assume that we know the formula for the falling object. Afterwards, we will derive it.</p>
</div>
<div class="section" id="our-python-encounter">
<h2>Our Python Encounter<a class="headerlink" href="#our-python-encounter" title="Permalink to this headline"></a></h2>
<p>We start with preparing folders for storing our calculations, figures and if needed, specific data files we use as input or output files.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="c1"># Common imports</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="c1"># Where to save the figures and data files</span>
<span class="n">PROJECT_ROOT_DIR</span> <span class="o">=</span> <span class="s2">&quot;Results&quot;</span>
<span class="n">FIGURE_ID</span> <span class="o">=</span> <span class="s2">&quot;Results/FigureFiles&quot;</span>
<span class="n">DATA_ID</span> <span class="o">=</span> <span class="s2">&quot;DataFiles/&quot;</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">PROJECT_ROOT_DIR</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">PROJECT_ROOT_DIR</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">image_path</span><span class="p">(</span><span class="n">fig_id</span><span class="p">):</span>
<span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">,</span> <span class="n">fig_id</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">data_path</span><span class="p">(</span><span class="n">dat_id</span><span class="p">):</span>
<span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">,</span> <span class="n">dat_id</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">save_fig</span><span class="p">(</span><span class="n">fig_id</span><span class="p">):</span>
<span class="n">plt</span><span class="o">.</span><span class="n">savefig</span><span class="p">(</span><span class="n">image_path</span><span class="p">(</span><span class="n">fig_id</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot;.png&quot;</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;png&#39;</span><span class="p">)</span>
<span class="c1">#in case we have an input file we wish to read in</span>
<span class="c1">#infile = open(data_path(&quot;MassEval2016.dat&quot;),&#39;r&#39;)</span>
</pre></div>
</div>
</div>
</div>
<p>You could also define a function for making our plots. You
can obviously avoid this and simply set up various <strong>matplotlib</strong>
commands every time you need them. You may however find it convenient
to collect all such commands in one function and simply call this
function.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">pylab</span> <span class="kn">import</span> <span class="n">plt</span><span class="p">,</span> <span class="n">mpl</span>
<span class="n">plt</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">use</span><span class="p">(</span><span class="s1">&#39;seaborn&#39;</span><span class="p">)</span>
<span class="n">mpl</span><span class="o">.</span><span class="n">rcParams</span><span class="p">[</span><span class="s1">&#39;font.family&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;serif&#39;</span>
<span class="k">def</span> <span class="nf">MakePlot</span><span class="p">(</span><span class="n">x</span><span class="p">,</span><span class="n">y</span><span class="p">,</span> <span class="n">styles</span><span class="p">,</span> <span class="n">labels</span><span class="p">,</span> <span class="n">axlabels</span><span class="p">):</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span><span class="mi">6</span><span class="p">))</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)):</span>
<span class="n">plt</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">styles</span><span class="p">[</span><span class="n">i</span><span class="p">],</span> <span class="n">label</span> <span class="o">=</span> <span class="n">labels</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="n">axlabels</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="n">axlabels</span><span class="p">[</span><span class="mi">1</span><span class="p">])</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">loc</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Thereafter we start setting up the code for the falling object.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="o">%</span><span class="k">matplotlib</span> inline
<span class="kn">import</span> <span class="nn">matplotlib.patches</span> <span class="k">as</span> <span class="nn">mpatches</span>
<span class="n">g</span> <span class="o">=</span> <span class="mf">9.80655</span> <span class="c1">#m/s^2</span>
<span class="n">y_0</span> <span class="o">=</span> <span class="mf">10.0</span> <span class="c1"># initial position in meters</span>
<span class="n">DeltaT</span> <span class="o">=</span> <span class="mf">0.1</span> <span class="c1"># time step</span>
<span class="c1"># final time when y = 0, t = sqrt(2*10/g)</span>
<span class="n">tfinal</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">sqrt</span><span class="p">(</span><span class="mf">2.0</span><span class="o">*</span><span class="n">y_0</span><span class="o">/</span><span class="n">g</span><span class="p">)</span>
<span class="c1">#set up arrays </span>
<span class="n">t</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span><span class="n">tfinal</span><span class="p">,</span><span class="n">DeltaT</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span><span class="n">y_0</span> <span class="o">-</span><span class="n">g</span><span class="o">*.</span><span class="mi">5</span><span class="o">*</span><span class="n">t</span><span class="o">**</span><span class="mi">2</span>
<span class="c1"># Then make a nice printout in table form using Pandas</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">IPython.display</span> <span class="kn">import</span> <span class="n">display</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;t[s]&#39;</span><span class="p">:</span> <span class="n">t</span><span class="p">,</span>
<span class="s1">&#39;y[m]&#39;</span><span class="p">:</span> <span class="n">y</span>
<span class="p">}</span>
<span class="n">RawData</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">RawData</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">use</span><span class="p">(</span><span class="s1">&#39;ggplot&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">figure</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">8</span><span class="p">,</span><span class="mi">8</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">scatter</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">color</span> <span class="o">=</span> <span class="s1">&#39;b&#39;</span><span class="p">)</span>
<span class="n">blue_patch</span> <span class="o">=</span> <span class="n">mpatches</span><span class="o">.</span><span class="n">Patch</span><span class="p">(</span><span class="n">color</span> <span class="o">=</span> <span class="s1">&#39;b&#39;</span><span class="p">,</span> <span class="n">label</span> <span class="o">=</span> <span class="s1">&#39;Height y as function of time t&#39;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">legend</span><span class="p">(</span><span class="n">handles</span><span class="o">=</span><span class="p">[</span><span class="n">blue_patch</span><span class="p">])</span>
<span class="n">plt</span><span class="o">.</span><span class="n">xlabel</span><span class="p">(</span><span class="s2">&quot;t[s]&quot;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">ylabel</span><span class="p">(</span><span class="s2">&quot;y[m]&quot;</span><span class="p">)</span>
<span class="n">save_fig</span><span class="p">(</span><span class="s2">&quot;FallingBaseball&quot;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_html"><div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>t[s]</th>
<th>y[m]</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.0</td>
<td>10.000000</td>
</tr>
<tr>
<th>1</th>
<td>0.1</td>
<td>9.950967</td>
</tr>
<tr>
<th>2</th>
<td>0.2</td>
<td>9.803869</td>
</tr>
<tr>
<th>3</th>
<td>0.3</td>
<td>9.558705</td>
</tr>
<tr>
<th>4</th>
<td>0.4</td>
<td>9.215476</td>
</tr>
<tr>
<th>5</th>
<td>0.5</td>
<td>8.774181</td>
</tr>
<tr>
<th>6</th>
<td>0.6</td>
<td>8.234821</td>
</tr>
<tr>
<th>7</th>
<td>0.7</td>
<td>7.597395</td>
</tr>
<tr>
<th>8</th>
<td>0.8</td>
<td>6.861904</td>
</tr>
<tr>
<th>9</th>
<td>0.9</td>
<td>6.028347</td>
</tr>
<tr>
<th>10</th>
<td>1.0</td>
<td>5.096725</td>
</tr>
<tr>
<th>11</th>
<td>1.1</td>
<td>4.067037</td>
</tr>
<tr>
<th>12</th>
<td>1.2</td>
<td>2.939284</td>
</tr>
<tr>
<th>13</th>
<td>1.3</td>
<td>1.713465</td>
</tr>
<tr>
<th>14</th>
<td>1.4</td>
<td>0.389581</td>
</tr>
</tbody>
</table>
</div></div><img alt="../_images/chapter2_25_11.png" src="../_images/chapter2_25_11.png" />
</div>
</div>
<p>Here we used <strong>pandas</strong> (see below) to systemize the output of the position as function of time.</p>
</div>
<div class="section" id="average-quantities">
<h2>Average quantities<a class="headerlink" href="#average-quantities" title="Permalink to this headline"></a></h2>
<p>We define now the average velocity as</p>
<div class="math notranslate nohighlight">
\[
\overline{v}(t) = \frac{y(t+\Delta t)-y(t)}{\Delta t}.
\]</div>
<p>In the code we have set the time step <span class="math notranslate nohighlight">\(\Delta t\)</span> to a given value. We could define it in terms of the number of points <span class="math notranslate nohighlight">\(n\)</span> as</p>
<div class="math notranslate nohighlight">
\[
\Delta t = \frac{t_{\mathrm{final}-}t_{\mathrm{initial}}}{n+1}.
\]</div>
<p>Since we have discretized the variables, we introduce the counter <span class="math notranslate nohighlight">\(i\)</span> and let <span class="math notranslate nohighlight">\(y(t)\rightarrow y(t_i)=y_i\)</span> and <span class="math notranslate nohighlight">\(t\rightarrow t_i\)</span>
with <span class="math notranslate nohighlight">\(i=0,1,\dots, n\)</span>. This gives us the following shorthand notations that we will use for the rest of this course. We define</p>
<div class="math notranslate nohighlight">
\[
y_i = y(t_i),\hspace{0.2cm} i=0,1,2,\dots,n.
\]</div>
<p>This applies to other variables which depend on say time. Examples are the velocities, accelerations, momenta etc.
Furthermore we use the shorthand</p>
<div class="math notranslate nohighlight">
\[
y_{i\pm 1} = y(t_i\pm \Delta t),\hspace{0.12cm} i=0,1,2,\dots,n.
\]</div>
</div>
<div class="section" id="compact-equations">
<h2>Compact equations<a class="headerlink" href="#compact-equations" title="Permalink to this headline"></a></h2>
<p>We can then rewrite in a more compact form the average velocity as</p>
<div class="math notranslate nohighlight">
\[
\overline{v}_i = \frac{y_{i+1}-y_{i}}{\Delta t}.
\]</div>
<p>The velocity is defined as the change in position per unit time.
In the limit <span class="math notranslate nohighlight">\(\Delta t \rightarrow 0\)</span> this defines the instantaneous velocity, which is nothing but the slope of the position at a time <span class="math notranslate nohighlight">\(t\)</span>.
We have thus</p>
<div class="math notranslate nohighlight">
\[
v(t) = \frac{dy}{dt}=\lim_{\Delta t \rightarrow 0}\frac{y(t+\Delta t)-y(t)}{\Delta t}.
\]</div>
<p>Similarly, we can define the average acceleration as the change in velocity per unit time as</p>
<div class="math notranslate nohighlight">
\[
\overline{a}_i = \frac{v_{i+1}-v_{i}}{\Delta t},
\]</div>
<p>resulting in the instantaneous acceleration</p>
<div class="math notranslate nohighlight">
\[
a(t) = \frac{dv}{dt}=\lim_{\Delta t\rightarrow 0}\frac{v(t+\Delta t)-v(t)}{\Delta t}.
\]</div>
<p><strong>A note on notations</strong>: When writing for example the velocity as <span class="math notranslate nohighlight">\(v(t)\)</span> we are then referring to the continuous and instantaneous value. A subscript like
<span class="math notranslate nohighlight">\(v_i\)</span> refers always to the discretized values.</p>
</div>
<div class="section" id="a-differential-equation">
<h2>A differential equation<a class="headerlink" href="#a-differential-equation" title="Permalink to this headline"></a></h2>
<p>We can rewrite the instantaneous acceleration as</p>
<div class="math notranslate nohighlight">
\[
a(t) = \frac{dv}{dt}=\frac{d}{dt}\frac{dy}{dt}=\frac{d^2y}{dt^2}.
\]</div>
<p>This forms the starting point for our definition of forces later. It is a famous second-order differential equation. If the acceleration is constant we can now recover the formula for the falling ball we started with.
The acceleration can depend on the position and the velocity. To be more formal we should then write the above differential equation as</p>
<div class="math notranslate nohighlight">
\[
\frac{d^2y}{dt^2}=a(t,y(t),\frac{dy}{dt}).
\]</div>
<p>With given initial conditions for <span class="math notranslate nohighlight">\(y(t_0)\)</span> and <span class="math notranslate nohighlight">\(v(t_0)\)</span> we can then
integrate the above equation and find the velocities and positions at
a given time <span class="math notranslate nohighlight">\(t\)</span>.</p>
<p>If we multiply with mass, we have one of the famous expressions for Newtons second law,</p>
<div class="math notranslate nohighlight">
\[
F(y,v,t)=m\frac{d^2y}{dt^2}=ma(t,y(t),\frac{dy}{dt}),
\]</div>
<p>where <span class="math notranslate nohighlight">\(F\)</span> is the force acting on an object with mass <span class="math notranslate nohighlight">\(m\)</span>. We see that it also has the right dimension, mass times length divided by time squared.
We will come back to this soon.</p>
</div>
<div class="section" id="integrating-our-equations">
<h2>Integrating our equations<a class="headerlink" href="#integrating-our-equations" title="Permalink to this headline"></a></h2>
<p>Formally we can then, starting with the acceleration (suppose we have measured it, how could we do that?)
compute say the height of a building. To see this we perform the following integrations from an initial time <span class="math notranslate nohighlight">\(t_0\)</span> to a given time <span class="math notranslate nohighlight">\(t\)</span></p>
<div class="math notranslate nohighlight">
\[
\int_{t_0}^t dt a(t) = \int_{t_0}^t dt \frac{dv}{dt} = v(t)-v(t_0),
\]</div>
<p>or as</p>
<div class="math notranslate nohighlight">
\[
v(t)=v(t_0)+\int_{t_0}^t dt a(t).
\]</div>
<p>When we know the velocity as function of time, we can find the position as function of time starting from the defintion of velocity as the derivative with respect to time, that is we have</p>
<div class="math notranslate nohighlight">
\[
\int_{t_0}^t dt v(t) = \int_{t_0}^t dt \frac{dy}{dt} = y(t)-y(t_0),
\]</div>
<p>or as</p>
<div class="math notranslate nohighlight">
\[
y(t)=y(t_0)+\int_{t_0}^t dt v(t).
\]</div>
<p>These equations define what is called the integration method for
finding the position and the velocity as functions of time. There is
no loss of generality if we extend these equations to more than one
spatial dimension.</p>
</div>
<div class="section" id="constant-acceleration-case-the-velocity">
<h2>Constant acceleration case, the velocity<a class="headerlink" href="#constant-acceleration-case-the-velocity" title="Permalink to this headline"></a></h2>
<p>Let us compute the velocity using the constant value for the acceleration given by <span class="math notranslate nohighlight">\(-g\)</span>. We have</p>
<div class="math notranslate nohighlight">
\[
v(t)=v(t_0)+\int_{t_0}^t dt a(t)=v(t_0)+\int_{t_0}^t dt (-g).
\]</div>
<p>Using our initial time as <span class="math notranslate nohighlight">\(t_0=0\)</span>s and setting the initial velocity <span class="math notranslate nohighlight">\(v(t_0)=v_0=0\)</span>m/s we get when integrating</p>
<div class="math notranslate nohighlight">
\[
v(t)=-gt.
\]</div>
<p>The more general case is</p>
<div class="math notranslate nohighlight">
\[
v(t)=v_0-g(t-t_0).
\]</div>
<p>We can then integrate the velocity and obtain the final formula for the position as function of time through</p>
<div class="math notranslate nohighlight">
\[
y(t)=y(t_0)+\int_{t_0}^t dt v(t)=y_0+\int_{t_0}^t dt v(t)=y_0+\int_{t_0}^t dt (-gt),
\]</div>
<p>With <span class="math notranslate nohighlight">\(y_0=10\)</span>m and <span class="math notranslate nohighlight">\(t_0=0\)</span>s, we obtain the equation we started with</p>
<div class="math notranslate nohighlight">
\[
y(t)=10-\frac{1}{2}gt^2.
\]</div>
</div>
<div class="section" id="computing-the-averages">
<h2>Computing the averages<a class="headerlink" href="#computing-the-averages" title="Permalink to this headline"></a></h2>
<p>After this mathematical background we are now ready to compute the mean velocity using our data.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Now we can compute the mean velocity using our data</span>
<span class="c1"># We define first an array Vaverage</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="n">Vaverage</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="n">Vaverage</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span><span class="o">-</span><span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="p">])</span><span class="o">/</span><span class="n">DeltaT</span>
<span class="c1"># Now we can compute the mean accelearatio using our data</span>
<span class="c1"># We define first an array Aaverage</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">size</span><span class="p">(</span><span class="n">t</span><span class="p">)</span>
<span class="n">Aaverage</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">Aaverage</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="o">-</span><span class="n">g</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">1</span><span class="p">,</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="n">Aaverage</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="n">Vaverage</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span><span class="o">-</span><span class="n">Vaverage</span><span class="p">[</span><span class="n">i</span><span class="p">])</span><span class="o">/</span><span class="n">DeltaT</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;t[s]&#39;</span><span class="p">:</span> <span class="n">t</span><span class="p">,</span>
<span class="s1">&#39;y[m]&#39;</span><span class="p">:</span> <span class="n">y</span><span class="p">,</span>
<span class="s1">&#39;v[m/s]&#39;</span><span class="p">:</span> <span class="n">Vaverage</span><span class="p">,</span>
<span class="s1">&#39;a[m/s^2]&#39;</span><span class="p">:</span> <span class="n">Aaverage</span>
<span class="p">}</span>
<span class="n">NewData</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">NewData</span><span class="p">[</span><span class="mi">0</span><span class="p">:</span><span class="n">n</span><span class="o">-</span><span class="mi">2</span><span class="p">])</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_html"><div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>t[s]</th>
<th>y[m]</th>
<th>v[m/s]</th>
<th>a[m/s^2]</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.0</td>
<td>10.000000</td>
<td>0.000000</td>
<td>-9.80655</td>
</tr>
<tr>
<th>1</th>
<td>0.1</td>
<td>9.950967</td>
<td>-1.470982</td>
<td>-9.80655</td>
</tr>
<tr>
<th>2</th>
<td>0.2</td>
<td>9.803869</td>
<td>-2.451638</td>
<td>-9.80655</td>
</tr>
<tr>
<th>3</th>
<td>0.3</td>
<td>9.558705</td>
<td>-3.432292</td>
<td>-9.80655</td>
</tr>
<tr>
<th>4</th>
<td>0.4</td>
<td>9.215476</td>
<td>-4.412948</td>
<td>-9.80655</td>
</tr>
<tr>
<th>5</th>
<td>0.5</td>
<td>8.774181</td>
<td>-5.393602</td>
<td>-9.80655</td>
</tr>
<tr>
<th>6</th>
<td>0.6</td>
<td>8.234821</td>
<td>-6.374258</td>
<td>-9.80655</td>
</tr>
<tr>
<th>7</th>
<td>0.7</td>
<td>7.597395</td>
<td>-7.354913</td>
<td>-9.80655</td>
</tr>
<tr>
<th>8</th>
<td>0.8</td>
<td>6.861904</td>
<td>-8.335567</td>
<td>-9.80655</td>
</tr>
<tr>
<th>9</th>
<td>0.9</td>
<td>6.028347</td>
<td>-9.316222</td>
<td>-9.80655</td>
</tr>
<tr>
<th>10</th>
<td>1.0</td>
<td>5.096725</td>
<td>-10.296878</td>
<td>-9.80655</td>
</tr>
<tr>
<th>11</th>
<td>1.1</td>
<td>4.067037</td>
<td>-11.277533</td>
<td>-9.80655</td>
</tr>
<tr>
<th>12</th>
<td>1.2</td>
<td>2.939284</td>
<td>-12.258187</td>
<td>-9.80655</td>
</tr>
</tbody>
</table>
</div></div></div>
</div>
<p>Note that we dont print the last values!</p>
</div>
<div class="section" id="including-air-resistance-in-our-model">
<h2>Including Air Resistance in our model<a class="headerlink" href="#including-air-resistance-in-our-model" title="Permalink to this headline"></a></h2>
<p>In our discussions till now of the falling baseball, we have ignored
air resistance and simply assumed that our system is only influenced
by the gravitational force. We will postpone the derivation of air
resistance till later, after our discussion of Newtons laws and
forces.</p>
<p>For our discussions here it suffices to state that the accelerations is now modified to</p>
<div class="math notranslate nohighlight">
\[
\boldsymbol{a}(t) = -g +D\boldsymbol{v}(t)\vert v(t)\vert,
\]</div>
<p>where <span class="math notranslate nohighlight">\(\vert v(t)\vert\)</span> is the absolute value of the velocity and <span class="math notranslate nohighlight">\(D\)</span> is a constant which pertains to the specific object we are studying.
Since we are dealing with motion in one dimension, we can simplify the above to</p>
<div class="math notranslate nohighlight">
\[
a(t) = -g +Dv^2(t).
\]</div>
<p>We can rewrite this as a differential equation</p>
<div class="math notranslate nohighlight">
\[
a(t) = \frac{dv}{dt}=\frac{d^2y}{dt^2}= -g +Dv^2(t).
\]</div>
<p>Using the integral equations discussed above we can integrate twice
and obtain first the velocity as function of time and thereafter the
position as function of time.</p>
<p>For this particular case, we can actually obtain an analytical
solution for the velocity and for the position. Here we will first
compute the solutions analytically, thereafter we will derive Eulers
method for solving these differential equations numerically.</p>
</div>
<div class="section" id="analytical-solutions">
<h2>Analytical solutions<a class="headerlink" href="#analytical-solutions" title="Permalink to this headline"></a></h2>
<p>For simplicity let us just write <span class="math notranslate nohighlight">\(v(t)\)</span> as <span class="math notranslate nohighlight">\(v\)</span>. We have</p>
<div class="math notranslate nohighlight">
\[
\frac{dv}{dt}= -g +Dv^2(t).
\]</div>
<p>We can solve this using the technique of separation of variables. We
isolate on the left all terms that involve <span class="math notranslate nohighlight">\(v\)</span> and on the right all
terms that involve time. We get then</p>
<div class="math notranslate nohighlight">
\[
\frac{dv}{g -Dv^2(t) }= -dt,
\]</div>
<p>We scale now the equation to the left by introducing a constant
<span class="math notranslate nohighlight">\(v_T=\sqrt{g/D}\)</span>. This constant has dimension length/time. Can you
show this?</p>
<p>Next we integrate the left-hand side (lhs) from <span class="math notranslate nohighlight">\(v_0=0\)</span> m/s to <span class="math notranslate nohighlight">\(v\)</span> and
the right-hand side (rhs) from <span class="math notranslate nohighlight">\(t_0=0\)</span> to <span class="math notranslate nohighlight">\(t\)</span> and obtain</p>
<div class="math notranslate nohighlight">
\[
\int_{0}^v\frac{dv}{g -Dv^2(t) }= \frac{v_T}{g}\mathrm{arctanh}(\frac{v}{v_T}) =-\int_0^tdt = -t.
\]</div>
<p>We can reorganize these equations as</p>
<div class="math notranslate nohighlight">
\[
v_T\mathrm{arctanh}(\frac{v}{v_T}) =-gt,
\]</div>
<p>which gives us <span class="math notranslate nohighlight">\(v\)</span> as function of time</p>
<div class="math notranslate nohighlight">
\[
v(t)=v_T\tanh{-(\frac{gt}{v_T})}.
\]</div>
</div>
<div class="section" id="finding-the-final-height">
<h2>Finding the final height<a class="headerlink" href="#finding-the-final-height" title="Permalink to this headline"></a></h2>
<p>With the velocity we can then find the height <span class="math notranslate nohighlight">\(y(t)\)</span> by integrating yet another time, that is</p>
<div class="math notranslate nohighlight">
\[
y(t)=y(t_0)+\int_{t_0}^t dt v(t)=\int_{0}^t dt[v_T\tanh{-(\frac{gt}{v_T})}].
\]</div>
<p>This integral is a little bit trickier but we can look it up in a table over
known integrals and we get</p>
<div class="math notranslate nohighlight">
\[
y(t)=y(t_0)-\frac{v_T^2}{g}\log{[\cosh{(\frac{gt}{v_T})}]}.
\]</div>
<p>Alternatively we could have used the symbolic Python package <strong>Sympy</strong> (example will be inserted later).</p>
<p>In most cases however, we need to revert to numerical solutions.</p>
</div>
<div class="section" id="our-first-attempt-at-solving-differential-equations">
<h2>Our first attempt at solving differential equations<a class="headerlink" href="#our-first-attempt-at-solving-differential-equations" title="Permalink to this headline"></a></h2>
<p>Here we will try the simplest possible approach to solving the second-order differential
equation</p>
<div class="math notranslate nohighlight">
\[
a(t) =\frac{d^2y}{dt^2}= -g +Dv^2(t).
\]</div>
<p>We rewrite it as two coupled first-order equations (this is a standard approach)</p>
<div class="math notranslate nohighlight">
\[
\frac{dy}{dt} = v(t),
\]</div>
<p>with initial condition <span class="math notranslate nohighlight">\(y(t_0)=y_0\)</span> and</p>
<div class="math notranslate nohighlight">
\[
a(t) =\frac{dv}{dt}= -g +Dv^2(t),
\]</div>
<p>with initial condition <span class="math notranslate nohighlight">\(v(t_0)=v_0\)</span>.</p>
<p>Many of the algorithms for solving differential equations start with simple Taylor equations.
If we now Taylor expand <span class="math notranslate nohighlight">\(y\)</span> and <span class="math notranslate nohighlight">\(v\)</span> around a value <span class="math notranslate nohighlight">\(t+\Delta t\)</span> we have</p>
<div class="math notranslate nohighlight">
\[
y(t+\Delta t) = y(t)+\Delta t \frac{dy}{dt}+\frac{\Delta t^2}{2!} \frac{d^2y}{dt^2}+O(\Delta t^3),
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
v(t+\Delta t) = v(t)+\Delta t \frac{dv}{dt}+\frac{\Delta t^2}{2!} \frac{d^2v}{dt^2}+O(\Delta t^3).
\]</div>
<p>Using the fact that <span class="math notranslate nohighlight">\(dy/dt = v\)</span> and <span class="math notranslate nohighlight">\(dv/dt=a\)</span> and keeping only terms up to <span class="math notranslate nohighlight">\(\Delta t\)</span> we have</p>
<div class="math notranslate nohighlight">
\[
y(t+\Delta t) = y(t)+\Delta t v(t)+O(\Delta t^2),
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
v(t+\Delta t) = v(t)+\Delta t a(t)+O(\Delta t^2).
\]</div>
</div>
<div class="section" id="discretizing-our-equations">
<h2>Discretizing our equations<a class="headerlink" href="#discretizing-our-equations" title="Permalink to this headline"></a></h2>
<p>Using our discretized versions of the equations with for example
<span class="math notranslate nohighlight">\(y_{i}=y(t_i)\)</span> and <span class="math notranslate nohighlight">\(y_{i\pm 1}=y(t_i+\Delta t)\)</span>, we can rewrite the
above equations as (and truncating at <span class="math notranslate nohighlight">\(\Delta t\)</span>)</p>
<div class="math notranslate nohighlight">
\[
y_{i+1} = y_i+\Delta t v_i,
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
v_{i+1} = v_i+\Delta t a_i.
\]</div>
<p>These are the famous Euler equations (forward Euler).</p>
<p>To solve these equations numerically we start at a time <span class="math notranslate nohighlight">\(t_0\)</span> and simply integrate up these equations to a final time <span class="math notranslate nohighlight">\(t_f\)</span>,
The step size <span class="math notranslate nohighlight">\(\Delta t\)</span> is an input parameter in our code.
You can define it directly in the code below as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">DeltaT</span> <span class="o">=</span> <span class="mf">0.1</span>
</pre></div>
</div>
</div>
</div>
<p>With a given final time <strong>tfinal</strong> we can then find the number of integration points via the <strong>ceil</strong> function included in the <strong>math</strong> package of Python
as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1">#define final time, assuming that initial time is zero</span>
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">ceil</span>
<span class="n">tfinal</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">ceil</span><span class="p">(</span><span class="n">tfinal</span><span class="o">/</span><span class="n">DeltaT</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>5
</pre></div>
</div>
</div>
</div>
<p>The <strong>ceil</strong> function returns the smallest integer not less than the input in say</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mf">21.15</span>
<span class="nb">print</span><span class="p">(</span><span class="n">ceil</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>22
</pre></div>
</div>
</div>
</div>
<p>which in the case here is 22.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">x</span> <span class="o">=</span> <span class="mf">21.75</span>
<span class="nb">print</span><span class="p">(</span><span class="n">ceil</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>22
</pre></div>
</div>
</div>
</div>
<p>which also yields 22. The <strong>floor</strong> function in the <strong>math</strong> package
is used to return the closest integer value which is less than or equal to the specified expression or value.
Compare the previous result to the usage of <strong>floor</strong></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">floor</span>
<span class="n">x</span> <span class="o">=</span> <span class="mf">21.75</span>
<span class="nb">print</span><span class="p">(</span><span class="n">floor</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>21
</pre></div>
</div>
</div>
</div>
<p>Alternatively, we can define ourselves the number of integration(mesh) points. In this case we could have</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">tinitial</span> <span class="o">=</span> <span class="mf">0.0</span>
<span class="n">tfinal</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="n">DeltaT</span> <span class="o">=</span> <span class="p">(</span><span class="n">tfinal</span><span class="o">-</span><span class="n">tinitial</span><span class="p">)</span><span class="o">/</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">DeltaT</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>0.05
</pre></div>
</div>
</div>
</div>
<p>Since we will set up one-dimensional arrays that contain the values of
various variables like time, position, velocity, acceleration etc, we
need to know the value of <span class="math notranslate nohighlight">\(n\)</span>, the number of data points (or
integration or mesh points). With <span class="math notranslate nohighlight">\(n\)</span> we can initialize a given array
by setting all elelements to zero, as done here</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># define array a</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[0. 0. 0. 0. 0. 0. 0. 0. 0. 0.]
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="code-for-implementing-euler-s-method">
<h2>Code for implementing Eulers method<a class="headerlink" href="#code-for-implementing-euler-s-method" title="Permalink to this headline"></a></h2>
<p>In the code here we implement this simple Eurler scheme choosing a value for <span class="math notranslate nohighlight">\(D=0.0245\)</span> m/s.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="c1"># Common imports</span>
<span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="o">*</span>
<span class="kn">import</span> <span class="nn">matplotlib.pyplot</span> <span class="k">as</span> <span class="nn">plt</span>
<span class="kn">import</span> <span class="nn">os</span>
<span class="c1"># Where to save the figures and data files</span>
<span class="n">PROJECT_ROOT_DIR</span> <span class="o">=</span> <span class="s2">&quot;Results&quot;</span>
<span class="n">FIGURE_ID</span> <span class="o">=</span> <span class="s2">&quot;Results/FigureFiles&quot;</span>
<span class="n">DATA_ID</span> <span class="o">=</span> <span class="s2">&quot;DataFiles/&quot;</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">PROJECT_ROOT_DIR</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">mkdir</span><span class="p">(</span><span class="n">PROJECT_ROOT_DIR</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">)</span>
<span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">):</span>
<span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">image_path</span><span class="p">(</span><span class="n">fig_id</span><span class="p">):</span>
<span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">FIGURE_ID</span><span class="p">,</span> <span class="n">fig_id</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">data_path</span><span class="p">(</span><span class="n">dat_id</span><span class="p">):</span>
<span class="k">return</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">DATA_ID</span><span class="p">,</span> <span class="n">dat_id</span><span class="p">)</span>
<span class="k">def</span> <span class="nf">save_fig</span><span class="p">(</span><span class="n">fig_id</span><span class="p">):</span>
<span class="n">plt</span><span class="o">.</span><span class="n">savefig</span><span class="p">(</span><span class="n">image_path</span><span class="p">(</span><span class="n">fig_id</span><span class="p">)</span> <span class="o">+</span> <span class="s2">&quot;.png&quot;</span><span class="p">,</span> <span class="nb">format</span><span class="o">=</span><span class="s1">&#39;png&#39;</span><span class="p">)</span>
<span class="n">g</span> <span class="o">=</span> <span class="mf">9.80655</span> <span class="c1">#m/s^2</span>
<span class="n">D</span> <span class="o">=</span> <span class="mf">0.00245</span> <span class="c1">#m/s</span>
<span class="n">DeltaT</span> <span class="o">=</span> <span class="mf">0.1</span>
<span class="c1">#set up arrays </span>
<span class="n">tfinal</span> <span class="o">=</span> <span class="mf">0.5</span>
<span class="n">n</span> <span class="o">=</span> <span class="n">ceil</span><span class="p">(</span><span class="n">tfinal</span><span class="o">/</span><span class="n">DeltaT</span><span class="p">)</span>
<span class="c1"># define scaling constant vT</span>
<span class="n">vT</span> <span class="o">=</span> <span class="n">sqrt</span><span class="p">(</span><span class="n">g</span><span class="o">/</span><span class="n">D</span><span class="p">)</span>
<span class="c1"># set up arrays for t, a, v, and y and we can compare our results with analytical ones</span>
<span class="n">t</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">v</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">y</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="n">yanalytic</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">n</span><span class="p">)</span>
<span class="c1"># Initial conditions</span>
<span class="n">v</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mf">0.0</span> <span class="c1">#m/s</span>
<span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="mf">10.0</span> <span class="c1">#m</span>
<span class="n">yanalytic</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span>
<span class="c1"># Start integrating using Euler&#39;s method</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="c1"># expression for acceleration</span>
<span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="o">-</span><span class="n">g</span> <span class="o">+</span> <span class="n">D</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="c1"># update velocity and position</span>
<span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">DeltaT</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">DeltaT</span><span class="o">*</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="c1"># update time to next time step and compute analytical answer</span>
<span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">DeltaT</span>
<span class="n">yanalytic</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">-</span><span class="p">(</span><span class="n">vT</span><span class="o">*</span><span class="n">vT</span><span class="o">/</span><span class="n">g</span><span class="p">)</span><span class="o">*</span><span class="n">log</span><span class="p">(</span><span class="n">cosh</span><span class="p">(</span><span class="n">g</span><span class="o">*</span><span class="n">t</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span><span class="o">/</span><span class="n">vT</span><span class="p">))</span>
<span class="k">if</span> <span class="p">(</span> <span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">&lt;</span> <span class="mf">0.0</span><span class="p">):</span>
<span class="k">break</span>
<span class="n">a</span><span class="p">[</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="o">-</span><span class="n">g</span> <span class="o">+</span> <span class="n">D</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;t[s]&#39;</span><span class="p">:</span> <span class="n">t</span><span class="p">,</span>
<span class="s1">&#39;y[m]&#39;</span><span class="p">:</span> <span class="n">y</span><span class="o">-</span><span class="n">yanalytic</span><span class="p">,</span>
<span class="s1">&#39;v[m/s]&#39;</span><span class="p">:</span> <span class="n">v</span><span class="p">,</span>
<span class="s1">&#39;a[m/s^2]&#39;</span><span class="p">:</span> <span class="n">a</span>
<span class="p">}</span>
<span class="n">NewData</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">NewData</span><span class="p">)</span>
<span class="c1">#finally we plot the data</span>
<span class="n">fig</span><span class="p">,</span> <span class="n">axs</span> <span class="o">=</span> <span class="n">plt</span><span class="o">.</span><span class="n">subplots</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">1</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">y</span><span class="p">,</span> <span class="n">t</span><span class="p">,</span> <span class="n">yanalytic</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">set_xlim</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="n">tfinal</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s1">&#39;y and exact&#39;</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">v</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s1">&#39;v[m/s]&#39;</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">t</span><span class="p">,</span> <span class="n">a</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">set_xlabel</span><span class="p">(</span><span class="s1">&#39;time[s]&#39;</span><span class="p">)</span>
<span class="n">axs</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span><span class="o">.</span><span class="n">set_ylabel</span><span class="p">(</span><span class="s1">&#39;a[m/s^2]&#39;</span><span class="p">)</span>
<span class="n">fig</span><span class="o">.</span><span class="n">tight_layout</span><span class="p">()</span>
<span class="n">save_fig</span><span class="p">(</span><span class="s2">&quot;EulerIntegration&quot;</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output text_html"><div>
<style scoped>
.dataframe tbody tr th:only-of-type {
vertical-align: middle;
}
.dataframe tbody tr th {
vertical-align: top;
}
.dataframe thead th {
text-align: right;
}
</style>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>t[s]</th>
<th>y[m]</th>
<th>v[m/s]</th>
<th>a[m/s^2]</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>0.0</td>
<td>0.000000</td>
<td>0.000000</td>
<td>-9.806550</td>
</tr>
<tr>
<th>1</th>
<td>0.1</td>
<td>0.049031</td>
<td>-0.980655</td>
<td>-9.804194</td>
</tr>
<tr>
<th>2</th>
<td>0.2</td>
<td>0.098034</td>
<td>-1.961074</td>
<td>-9.797128</td>
</tr>
<tr>
<th>3</th>
<td>0.3</td>
<td>0.146963</td>
<td>-2.940787</td>
<td>-9.785362</td>
</tr>
<tr>
<th>4</th>
<td>0.4</td>
<td>0.195770</td>
<td>-3.919323</td>
<td>-9.768915</td>
</tr>
</tbody>
</table>
</div></div><img alt="../_images/chapter2_121_11.png" src="../_images/chapter2_121_11.png" />
</div>
</div>
<p>Try different values for <span class="math notranslate nohighlight">\(\Delta t\)</span> and study the difference between the exact solution and the numerical solution.</p>
</div>
<div class="section" id="simple-extension-the-euler-cromer-method">
<h2>Simple extension, the Euler-Cromer method<a class="headerlink" href="#simple-extension-the-euler-cromer-method" title="Permalink to this headline"></a></h2>
<p>The Euler-Cromer method is a simple variant of the standard Euler
method. We use the newly updated velocity <span class="math notranslate nohighlight">\(v_{i+1}\)</span> as an input to the
new position, that is, instead of</p>
<div class="math notranslate nohighlight">
\[
y_{i+1} = y_i+\Delta t v_i,
\]</div>
<p>and</p>
<div class="math notranslate nohighlight">
\[
v_{i+1} = v_i+\Delta t a_i,
\]</div>
<p>we use now the newly calculate for <span class="math notranslate nohighlight">\(v_{i+1}\)</span> as input to <span class="math notranslate nohighlight">\(y_{i+1}\)</span>, that is
we compute first</p>
<div class="math notranslate nohighlight">
\[
v_{i+1} = v_i+\Delta t a_i,
\]</div>
<p>and then</p>
<div class="math notranslate nohighlight">
\[
y_{i+1} = y_i+\Delta t v_{i+1},
\]</div>
<p>Implementing the Euler-Cromer method yields a simple change to the previous code. We only need to change the following line in the loop over time
steps</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">n</span><span class="o">-</span><span class="mi">1</span><span class="p">):</span>
<span class="c1"># more codes in between here</span>
<span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">DeltaT</span><span class="o">*</span><span class="n">a</span><span class="p">[</span><span class="n">i</span><span class="p">]</span>
<span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="n">y</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">DeltaT</span><span class="o">*</span><span class="n">v</span><span class="p">[</span><span class="n">i</span><span class="o">+</span><span class="mi">1</span><span class="p">]</span>
<span class="c1"># more code</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="python-practicalities-software-and-needed-installations">
<h2>Python practicalities, Software and needed installations<a class="headerlink" href="#python-practicalities-software-and-needed-installations" title="Permalink to this headline"></a></h2>
<p>We will make extensive use of Python as programming language and its
myriad of available libraries. You will find
Jupyter notebooks invaluable in your work.</p>
<p>If you have Python installed (we strongly recommend Python3) and you feel
pretty familiar with installing different packages, we recommend that
you install the following Python packages via <strong>pip</strong> as</p>
<ol class="simple">
<li><p>pip install numpy scipy matplotlib ipython scikit-learn mglearn sympy pandas pillow</p></li>
</ol>
<p>For Python3, replace <strong>pip</strong> with <strong>pip3</strong>.</p>
<p>For OSX users we recommend, after having installed Xcode, to
install <strong>brew</strong>. Brew allows for a seamless installation of additional
software via for example</p>
<ol class="simple">
<li><p>brew install python3</p></li>
</ol>
<p>For Linux users, with its variety of distributions like for example the widely popular Ubuntu distribution,
you can use <strong>pip</strong> as well and simply install Python as</p>
<ol class="simple">
<li><p>sudo apt-get install python3 (or python for pyhton2.7)</p></li>
</ol>
<p>etc etc.</p>
</div>
<div class="section" id="python-installers">
<h2>Python installers<a class="headerlink" href="#python-installers" title="Permalink to this headline"></a></h2>
<p>If you dont want to perform these operations separately and venture
into the hassle of exploring how to set up dependencies and paths, we
recommend two widely used distrubutions which set up all relevant
dependencies for Python, namely</p>
<ul class="simple">
<li><p><a class="reference external" href="https://docs.anaconda.com/">Anaconda</a>,</p></li>
</ul>
<p>which is an open source
distribution of the Python and R programming languages for large-scale
data processing, predictive analytics, and scientific computing, that
aims to simplify package management and deployment. Package versions
are managed by the package management system <strong>conda</strong>.</p>
<ul class="simple">
<li><p><a class="reference external" href="https://www.enthought.com/product/canopy/">Enthought canopy</a></p></li>
</ul>
<p>is a Python
distribution for scientific and analytic computing distribution and
analysis environment, available for free and under a commercial
license.</p>
<p>Furthermore, <a class="reference external" href="https://colab.research.google.com/notebooks/welcome.ipynb">Googles Colab</a> is a free Jupyter notebook environment that requires
no setup and runs entirely in the cloud. Try it out!</p>
</div>
<div class="section" id="useful-python-libraries">
<h2>Useful Python libraries<a class="headerlink" href="#useful-python-libraries" title="Permalink to this headline"></a></h2>
<p>Here we list several useful Python libraries we strongly recommend (if you use anaconda many of these are already there)</p>
<ul class="simple">
<li><p><a class="reference external" href="https://www.numpy.org/">NumPy</a> is a highly popular library for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays</p></li>
<li><p><a class="reference external" href="https://pandas.pydata.org/">The pandas</a> library provides high-performance, easy-to-use data structures and data analysis tools</p></li>
<li><p><a class="reference external" href="http://xarray.pydata.org/en/stable/">Xarray</a> is a Python package that makes working with labelled multi-dimensional arrays simple, efficient, and fun!</p></li>
<li><p><a class="reference external" href="https://www.scipy.org/">Scipy</a> (pronounced “Sigh Pie”) is a Python-based ecosystem of open-source software for mathematics, science, and engineering.</p></li>
<li><p><a class="reference external" href="https://matplotlib.org/">Matplotlib</a> is a Python 2D plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.</p></li>
<li><p><a class="reference external" href="https://github.com/HIPS/autograd">Autograd</a> can automatically differentiate native Python and Numpy code. It can handle a large subset of Pythons features, including loops, ifs, recursion and closures, and it can even take derivatives of derivatives of derivatives</p></li>
<li><p><a class="reference external" href="https://www.sympy.org/en/index.html">SymPy</a> is a Python library for symbolic mathematics.</p></li>
<li><p><a class="reference external" href="https://scikit-learn.org/stable/">scikit-learn</a> has simple and efficient tools for machine learning, data mining and data analysis</p></li>
<li><p><a class="reference external" href="https://www.tensorflow.org/">TensorFlow</a> is a Python library for fast numerical computing created and released by Google</p></li>
<li><p><a class="reference external" href="https://keras.io/">Keras</a> is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano</p></li>
<li><p>And many more such as <a class="reference external" href="https://pytorch.org/">pytorch</a>, <a class="reference external" href="https://pypi.org/project/Theano/">Theano</a> etc</p></li>
</ul>
<p>Your jupyter notebook can easily be
converted into a nicely rendered <strong>PDF</strong> file or a Latex file for
further processing. For example, convert to latex as</p>
<div class="highlight-none notranslate"><div class="highlight"><pre><span></span> pycod jupyter nbconvert filename.ipynb --to latex
</pre></div>
</div>
<p>And to add more versatility, the Python package <a class="reference external" href="http://www.sympy.org/en/index.html">SymPy</a> is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) and is entirely written in Python.</p>
</div>
<div class="section" id="numpy-examples-and-important-matrix-and-vector-handling-packages">
<h2>Numpy examples and Important Matrix and vector handling packages<a class="headerlink" href="#numpy-examples-and-important-matrix-and-vector-handling-packages" title="Permalink to this headline"></a></h2>
<p>There are several central software libraries for linear algebra and eigenvalue problems. Several of the more
popular ones have been wrapped into ofter software packages like those from the widely used text <strong>Numerical Recipes</strong>. The original source codes in many of the available packages are often taken from the widely used
software package LAPACK, which follows two other popular packages
developed in the 1970s, namely EISPACK and LINPACK. We describe them shortly here.</p>
<ul class="simple">
<li><p>LINPACK: package for linear equations and least square problems.</p></li>
<li><p>LAPACK:package for solving symmetric, unsymmetric and generalized eigenvalue problems. From LAPACKs website <a class="reference external" href="http://www.netlib.org">http://www.netlib.org</a> it is possible to download for free all source codes from this library. Both C/C++ and Fortran versions are available.</p></li>
<li><p>BLAS (I, II and III): (Basic Linear Algebra Subprograms) are routines that provide standard building blocks for performing basic vector and matrix operations. Blas I is vector operations, II vector-matrix operations and III matrix-matrix operations. Highly parallelized and efficient codes, all available for download from <a class="reference external" href="http://www.netlib.org">http://www.netlib.org</a>.</p></li>
</ul>
</div>
<div class="section" id="basic-matrix-features">
<h2>Basic Matrix Features<a class="headerlink" href="#basic-matrix-features" title="Permalink to this headline"></a></h2>
<p><strong>Matrix properties reminder.</strong></p>
<div class="math notranslate nohighlight">
\[\begin{split}
\mathbf{A} =
\begin{bmatrix} a_{11} &amp; a_{12} &amp; a_{13} &amp; a_{14} \\
a_{21} &amp; a_{22} &amp; a_{23} &amp; a_{24} \\
a_{31} &amp; a_{32} &amp; a_{33} &amp; a_{34} \\
a_{41} &amp; a_{42} &amp; a_{43} &amp; a_{44}
\end{bmatrix}\qquad
\mathbf{I} =
\begin{bmatrix} 1 &amp; 0 &amp; 0 &amp; 0 \\
0 &amp; 1 &amp; 0 &amp; 0 \\
0 &amp; 0 &amp; 1 &amp; 0 \\
0 &amp; 0 &amp; 0 &amp; 1
\end{bmatrix}
\end{split}\]</div>
<p>The inverse of a matrix is defined by</p>
<div class="math notranslate nohighlight">
\[
\mathbf{A}^{-1} \cdot \mathbf{A} = I
\]</div>
<table border="1">
<thead>
<tr><th align="center"> Relations </th> <th align="center"> Name </th> <th align="center"> matrix elements </th> </tr>
</thead>
<tbody>
<tr><td align="center"> $A = A^{T}$ </td> <td align="center"> symmetric </td> <td align="center"> $a_{ij} = a_{ji}$ </td> </tr>
<tr><td align="center"> $A = \left (A^{T} \right )^{-1}$ </td> <td align="center"> real orthogonal </td> <td align="center"> $\sum_k a_{ik} a_{jk} = \sum_k a_{ki} a_{kj} = \delta_{ij}$ </td> </tr>
<tr><td align="center"> $A = A^{ * }$ </td> <td align="center"> real matrix </td> <td align="center"> $a_{ij} = a_{ij}^{ * }$ </td> </tr>
<tr><td align="center"> $A = A^{\dagger}$ </td> <td align="center"> hermitian </td> <td align="center"> $a_{ij} = a_{ji}^{ * }$ </td> </tr>
<tr><td align="center"> $A = \left (A^{\dagger} \right )^{-1}$ </td> <td align="center"> unitary </td> <td align="center"> $\sum_k a_{ik} a_{jk}^{ * } = \sum_k a_{ki}^{ * } a_{kj} = \delta_{ij}$ </td> </tr>
</tbody>
</table>
<div class="section" id="some-famous-matrices">
<h3>Some famous Matrices<a class="headerlink" href="#some-famous-matrices" title="Permalink to this headline"></a></h3>
<ul class="simple">
<li><p>Diagonal if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i\ne j\)</span></p></li>
<li><p>Upper triangular if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &gt; j\)</span></p></li>
<li><p>Lower triangular if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &lt; j\)</span></p></li>
<li><p>Upper Hessenberg if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &gt; j+1\)</span></p></li>
<li><p>Lower Hessenberg if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &lt; j+1\)</span></p></li>
<li><p>Tridiagonal if <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(|i -j| &gt; 1\)</span></p></li>
<li><p>Lower banded with bandwidth <span class="math notranslate nohighlight">\(p\)</span>: <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &gt; j+p\)</span></p></li>
<li><p>Upper banded with bandwidth <span class="math notranslate nohighlight">\(p\)</span>: <span class="math notranslate nohighlight">\(a_{ij}=0\)</span> for <span class="math notranslate nohighlight">\(i &lt; j+p\)</span></p></li>
<li><p>Banded, block upper triangular, block lower triangular….</p></li>
</ul>
</div>
<div class="section" id="more-basic-matrix-features">
<h3>More Basic Matrix Features<a class="headerlink" href="#more-basic-matrix-features" title="Permalink to this headline"></a></h3>
<p><strong>Some Equivalent Statements.</strong></p>
<p>For an <span class="math notranslate nohighlight">\(N\times N\)</span> matrix <span class="math notranslate nohighlight">\(\mathbf{A}\)</span> the following properties are all equivalent</p>
<ul class="simple">
<li><p>If the inverse of <span class="math notranslate nohighlight">\(\mathbf{A}\)</span> exists, <span class="math notranslate nohighlight">\(\mathbf{A}\)</span> is nonsingular.</p></li>
<li><p>The equation <span class="math notranslate nohighlight">\(\mathbf{Ax}=0\)</span> implies <span class="math notranslate nohighlight">\(\mathbf{x}=0\)</span>.</p></li>
<li><p>The rows of <span class="math notranslate nohighlight">\(\mathbf{A}\)</span> form a basis of <span class="math notranslate nohighlight">\(R^N\)</span>.</p></li>
<li><p>The columns of <span class="math notranslate nohighlight">\(\mathbf{A}\)</span> form a basis of <span class="math notranslate nohighlight">\(R^N\)</span>.</p></li>
<li><p><span class="math notranslate nohighlight">\(\mathbf{A}\)</span> is a product of elementary matrices.</p></li>
<li><p><span class="math notranslate nohighlight">\(0\)</span> is not eigenvalue of <span class="math notranslate nohighlight">\(\mathbf{A}\)</span>.</p></li>
</ul>
</div>
</div>
<div class="section" id="numpy-and-arrays">
<h2>Numpy and arrays<a class="headerlink" href="#numpy-and-arrays" title="Permalink to this headline"></a></h2>
<p><a class="reference external" href="http://www.numpy.org/">Numpy</a> provides an easy way to handle arrays in Python. The standard way to import this library is as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
</pre></div>
</div>
</div>
</div>
<p>Here follows a simple example where we set up an array of ten elements, all determined by random numbers drawn according to the normal distribution,</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">normal</span><span class="p">(</span><span class="n">size</span><span class="o">=</span><span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[-0.15903306 -1.03373868 0.31582494 -0.65395262 0.96308377 -0.89760255
1.62466988 1.27946914 -0.71331923 -0.2179017 ]
</pre></div>
</div>
</div>
</div>
<p>We defined a vector <span class="math notranslate nohighlight">\(x\)</span> with <span class="math notranslate nohighlight">\(n=10\)</span> elements with its values given by the Normal distribution <span class="math notranslate nohighlight">\(N(0,1)\)</span>.
Another alternative is to declare a vector as follows</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[1 2 3]
</pre></div>
</div>
</div>
</div>
<p>Here we have defined a vector with three elements, with <span class="math notranslate nohighlight">\(x_0=1\)</span>, <span class="math notranslate nohighlight">\(x_1=2\)</span> and <span class="math notranslate nohighlight">\(x_2=3\)</span>. Note that both Python and C++
start numbering array elements from <span class="math notranslate nohighlight">\(0\)</span> and on. This means that a vector with <span class="math notranslate nohighlight">\(n\)</span> elements has a sequence of entities <span class="math notranslate nohighlight">\(x_0, x_1, x_2, \dots, x_{n-1}\)</span>. We could also let (recommended) Numpy to compute the logarithms of a specific array as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">]))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[1.38629436 1.94591015 2.07944154]
</pre></div>
</div>
</div>
</div>
<p>In the last example we used Numpys unary function <span class="math notranslate nohighlight">\(np.log\)</span>. This function is
highly tuned to compute array elements since the code is vectorized
and does not require looping. We normaly recommend that you use the
Numpy intrinsic functions instead of the corresponding <strong>log</strong> function
from Pythons <strong>math</strong> module. The looping is done explicitely by the
<strong>np.log</strong> function. The alternative, and slower way to compute the
logarithms of a vector would be to write</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">from</span> <span class="nn">math</span> <span class="kn">import</span> <span class="n">log</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">])</span>
<span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="mi">0</span><span class="p">,</span> <span class="nb">len</span><span class="p">(</span><span class="n">x</span><span class="p">)):</span>
<span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">=</span> <span class="n">log</span><span class="p">(</span><span class="n">x</span><span class="p">[</span><span class="n">i</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[1 1 2]
</pre></div>
</div>
</div>
</div>
<p>We note that our code is much longer already and we need to import the <strong>log</strong> function from the <strong>math</strong> module.
The attentive reader will also notice that the output is <span class="math notranslate nohighlight">\([1, 1, 2]\)</span>. Python interprets automagically our numbers as integers (like the <strong>automatic</strong> keyword in C++). To change this we could define our array elements to be double precision numbers as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mi">4</span><span class="p">,</span> <span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">],</span> <span class="n">dtype</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">float64</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output stream highlight-myst-ansi notranslate"><div class="highlight"><pre><span></span>[1.38629436 1.94591015 2.07944154]
</pre></div>
</div>
</div>
</div>
<p>or simply write them as double precision numbers (Python uses 64 bits as default for floating point type variables), that is</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">,</span> <span class="mf">8.0</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
</pre></div>
</div>
</div>
<div class="cell_output docutils container">
<div class="output traceback highlight-ipythontb notranslate"><div class="highlight"><pre><span></span><span class="gt"> File</span><span class="nn"> &quot;&lt;ipython-input-20-f6d7a289d493&gt;&quot;</span><span class="gt">, line </span><span class="mi">3</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="p">)</span>
<span class="o">^</span>
<span class="ne">SyntaxError</span>: invalid syntax
</pre></div>
</div>
</div>
</div>
<p>To check the number of bytes (remember that one byte contains eight bits for double precision variables), you can use simple use the <strong>itemsize</strong> functionality (the array <span class="math notranslate nohighlight">\(x\)</span> is actually an object which inherits the functionalities defined in Numpy) as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">x</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">,</span> <span class="mf">8.0</span><span class="p">])</span>
<span class="nb">print</span><span class="p">(</span><span class="n">x</span><span class="o">.</span><span class="n">itemsize</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="matrices-in-python">
<h2>Matrices in Python<a class="headerlink" href="#matrices-in-python" title="Permalink to this headline"></a></h2>
<p>Having defined vectors, we are now ready to try out matrices. We can
define a <span class="math notranslate nohighlight">\(3 \times 3 \)</span> real matrix <span class="math notranslate nohighlight">\(\hat{A}\)</span> as (recall that we user
lowercase letters for vectors and uppercase letters for matrices)</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">,</span> <span class="mf">8.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">3.0</span><span class="p">,</span> <span class="mf">10.0</span><span class="p">,</span> <span class="mf">11.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">]</span> <span class="p">]))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>If we use the <strong>shape</strong> function we would get <span class="math notranslate nohighlight">\((3, 3)\)</span> as output, that is verifying that our matrix is a <span class="math notranslate nohighlight">\(3\times 3\)</span> matrix. We can slice the matrix and print for example the first column (Python organized matrix elements in a row-major order, see below) as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">,</span> <span class="mf">8.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">3.0</span><span class="p">,</span> <span class="mf">10.0</span><span class="p">,</span> <span class="mf">11.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">]</span> <span class="p">]))</span>
<span class="c1"># print the first column, row-major order and elements start with 0</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">[:,</span><span class="mi">0</span><span class="p">])</span>
</pre></div>
</div>
</div>
</div>
<p>We can continue this was by printing out other columns or rows. The example here prints out the second column</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">log</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">([</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">,</span> <span class="mf">8.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">3.0</span><span class="p">,</span> <span class="mf">10.0</span><span class="p">,</span> <span class="mf">11.0</span><span class="p">],</span> <span class="p">[</span><span class="mf">4.0</span><span class="p">,</span> <span class="mf">5.0</span><span class="p">,</span> <span class="mf">7.0</span><span class="p">]</span> <span class="p">]))</span>
<span class="c1"># print the first column, row-major order and elements start with 0</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">[</span><span class="mi">1</span><span class="p">,:])</span>
</pre></div>
</div>
</div>
</div>
<p>Numpy contains many other functionalities that allow us to slice, subdivide etc etc arrays. We strongly recommend that you look up the <a class="reference external" href="http://www.numpy.org/">Numpy website for more details</a>. Useful functions when defining a matrix are the <strong>np.zeros</strong> function which declares a matrix of a given dimension and sets all elements to zero</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="c1"># define a matrix of dimension 10 x 10 and set all elements to zero</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span> <span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span> <span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>or initializing all elements to</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="c1"># define a matrix of dimension 10 x 10 and set all elements to one</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">ones</span><span class="p">(</span> <span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span> <span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>or as unitarily distributed random numbers (see the material on random number generators in the statistics part)</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="n">n</span> <span class="o">=</span> <span class="mi">10</span>
<span class="c1"># define a matrix of dimension 10 x 10 and set all elements to random numbers with x \in [0, 1]</span>
<span class="n">A</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">rand</span><span class="p">(</span><span class="n">n</span><span class="p">,</span> <span class="n">n</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">A</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
</div>
<div class="section" id="meet-the-pandas">
<h2>Meet the Pandas<a class="headerlink" href="#meet-the-pandas" title="Permalink to this headline"></a></h2>
<!-- dom:FIGURE: [fig/pandas.jpg, width=600 frac=0.8] -->
<!-- begin figure -->
<p></p>
<img src="fig/pandas.jpg" width=600>
<!-- end figure -->
<p>Another useful Python package is
<a class="reference external" href="https://pandas.pydata.org/">pandas</a>, which is an open source library
providing high-performance, easy-to-use data structures and data
analysis tools for Python. <strong>pandas</strong> stands for panel data, a term borrowed from econometrics and is an efficient library for data analysis with an emphasis on tabular data.
<strong>pandas</strong> has two major classes, the <strong>DataFrame</strong> class with two-dimensional data objects and tabular data organized in columns and the class <strong>Series</strong> with a focus on one-dimensional data objects. Both classes allow you to index data easily as we will see in the examples below.
<strong>pandas</strong> allows you also to perform mathematical operations on the data, spanning from simple reshapings of vectors and matrices to statistical operations.</p>
<p>The following simple example shows how we can, in an easy way make tables of our data. Here we define a data set which includes names, place of birth and date of birth, and displays the data in an easy to read way. We will see repeated use of <strong>pandas</strong>, in particular in connection with classification of data.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">IPython.display</span> <span class="kn">import</span> <span class="n">display</span>
<span class="n">data</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;First Name&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Frodo&quot;</span><span class="p">,</span> <span class="s2">&quot;Bilbo&quot;</span><span class="p">,</span> <span class="s2">&quot;Aragorn II&quot;</span><span class="p">,</span> <span class="s2">&quot;Samwise&quot;</span><span class="p">],</span>
<span class="s1">&#39;Last Name&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Baggins&quot;</span><span class="p">,</span> <span class="s2">&quot;Baggins&quot;</span><span class="p">,</span><span class="s2">&quot;Elessar&quot;</span><span class="p">,</span><span class="s2">&quot;Gamgee&quot;</span><span class="p">],</span>
<span class="s1">&#39;Place of birth&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Shire&quot;</span><span class="p">,</span> <span class="s2">&quot;Shire&quot;</span><span class="p">,</span> <span class="s2">&quot;Eriador&quot;</span><span class="p">,</span> <span class="s2">&quot;Shire&quot;</span><span class="p">],</span>
<span class="s1">&#39;Date of Birth T.A.&#39;</span><span class="p">:</span> <span class="p">[</span><span class="mi">2968</span><span class="p">,</span> <span class="mi">2890</span><span class="p">,</span> <span class="mi">2931</span><span class="p">,</span> <span class="mi">2980</span><span class="p">]</span>
<span class="p">}</span>
<span class="n">data_pandas</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">data_pandas</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>In the above we have imported <strong>pandas</strong> with the shorthand <strong>pd</strong>, the latter has become the standard way we import <strong>pandas</strong>. We make then a list of various variables
and reorganize the above lists into a <strong>DataFrame</strong> and then print out a neat table with specific column labels as <em>Name</em>, <em>place of birth</em> and <em>date of birth</em>.
Displaying these results, we see that the indices are given by the default numbers from zero to three.
<strong>pandas</strong> is extremely flexible and we can easily change the above indices by defining a new type of indexing as</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">data_pandas</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">data</span><span class="p">,</span><span class="n">index</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;Frodo&#39;</span><span class="p">,</span><span class="s1">&#39;Bilbo&#39;</span><span class="p">,</span><span class="s1">&#39;Aragorn&#39;</span><span class="p">,</span><span class="s1">&#39;Sam&#39;</span><span class="p">])</span>
<span class="n">display</span><span class="p">(</span><span class="n">data_pandas</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Thereafter we display the content of the row which begins with the index <strong>Aragorn</strong></p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">display</span><span class="p">(</span><span class="n">data_pandas</span><span class="o">.</span><span class="n">loc</span><span class="p">[</span><span class="s1">&#39;Aragorn&#39;</span><span class="p">])</span>
</pre></div>
</div>
</div>
</div>
<p>We can easily append data to this, for example</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">new_hobbit</span> <span class="o">=</span> <span class="p">{</span><span class="s1">&#39;First Name&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Peregrin&quot;</span><span class="p">],</span>
<span class="s1">&#39;Last Name&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Took&quot;</span><span class="p">],</span>
<span class="s1">&#39;Place of birth&#39;</span><span class="p">:</span> <span class="p">[</span><span class="s2">&quot;Shire&quot;</span><span class="p">],</span>
<span class="s1">&#39;Date of Birth T.A.&#39;</span><span class="p">:</span> <span class="p">[</span><span class="mi">2990</span><span class="p">]</span>
<span class="p">}</span>
<span class="n">data_pandas</span><span class="o">=</span><span class="n">data_pandas</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">new_hobbit</span><span class="p">,</span> <span class="n">index</span><span class="o">=</span><span class="p">[</span><span class="s1">&#39;Pippin&#39;</span><span class="p">]))</span>
<span class="n">display</span><span class="p">(</span><span class="n">data_pandas</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Here are other examples where we use the <strong>DataFrame</strong> functionality to handle arrays, now with more interesting features for us, namely numbers. We set up a matrix
of dimensionality <span class="math notranslate nohighlight">\(10\times 5\)</span> and compute the mean value and standard deviation of each column. Similarly, we can perform mathematial operations like squaring the matrix elements and many other operations.</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">numpy</span> <span class="k">as</span> <span class="nn">np</span>
<span class="kn">import</span> <span class="nn">pandas</span> <span class="k">as</span> <span class="nn">pd</span>
<span class="kn">from</span> <span class="nn">IPython.display</span> <span class="kn">import</span> <span class="n">display</span>
<span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">seed</span><span class="p">(</span><span class="mi">100</span><span class="p">)</span>
<span class="c1"># setting up a 10 x 5 matrix</span>
<span class="n">rows</span> <span class="o">=</span> <span class="mi">10</span>
<span class="n">cols</span> <span class="o">=</span> <span class="mi">5</span>
<span class="n">a</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">random</span><span class="o">.</span><span class="n">randn</span><span class="p">(</span><span class="n">rows</span><span class="p">,</span><span class="n">cols</span><span class="p">)</span>
<span class="n">df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">a</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">df</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df</span><span class="o">.</span><span class="n">mean</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df</span><span class="o">.</span><span class="n">std</span><span class="p">())</span>
<span class="n">display</span><span class="p">(</span><span class="n">df</span><span class="o">**</span><span class="mi">2</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>Thereafter we can select specific columns only and plot final results</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">df</span><span class="o">.</span><span class="n">columns</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;First&#39;</span><span class="p">,</span> <span class="s1">&#39;Second&#39;</span><span class="p">,</span> <span class="s1">&#39;Third&#39;</span><span class="p">,</span> <span class="s1">&#39;Fourth&#39;</span><span class="p">,</span> <span class="s1">&#39;Fifth&#39;</span><span class="p">]</span>
<span class="n">df</span><span class="o">.</span><span class="n">index</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">10</span><span class="p">)</span>
<span class="n">display</span><span class="p">(</span><span class="n">df</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df</span><span class="p">[</span><span class="s1">&#39;Second&#39;</span><span class="p">]</span><span class="o">.</span><span class="n">mean</span><span class="p">()</span> <span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df</span><span class="o">.</span><span class="n">info</span><span class="p">())</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df</span><span class="o">.</span><span class="n">describe</span><span class="p">())</span>
<span class="kn">from</span> <span class="nn">pylab</span> <span class="kn">import</span> <span class="n">plt</span><span class="p">,</span> <span class="n">mpl</span>
<span class="n">plt</span><span class="o">.</span><span class="n">style</span><span class="o">.</span><span class="n">use</span><span class="p">(</span><span class="s1">&#39;seaborn&#39;</span><span class="p">)</span>
<span class="n">mpl</span><span class="o">.</span><span class="n">rcParams</span><span class="p">[</span><span class="s1">&#39;font.family&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s1">&#39;serif&#39;</span>
<span class="n">df</span><span class="o">.</span><span class="n">cumsum</span><span class="p">()</span><span class="o">.</span><span class="n">plot</span><span class="p">(</span><span class="n">lw</span><span class="o">=</span><span class="mf">2.0</span><span class="p">,</span> <span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span><span class="mi">6</span><span class="p">))</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
<span class="n">df</span><span class="o">.</span><span class="n">plot</span><span class="o">.</span><span class="n">bar</span><span class="p">(</span><span class="n">figsize</span><span class="o">=</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span><span class="mi">6</span><span class="p">),</span> <span class="n">rot</span><span class="o">=</span><span class="mi">15</span><span class="p">)</span>
<span class="n">plt</span><span class="o">.</span><span class="n">show</span><span class="p">()</span>
</pre></div>
</div>
</div>
</div>
<p>We can produce a <span class="math notranslate nohighlight">\(4\times 4\)</span> matrix</p>
<div class="cell docutils container">
<div class="cell_input docutils container">
<div class="highlight-ipython3 notranslate"><div class="highlight"><pre><span></span><span class="n">b</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">16</span><span class="p">)</span><span class="o">.</span><span class="n">reshape</span><span class="p">((</span><span class="mi">4</span><span class="p">,</span><span class="mi">4</span><span class="p">))</span>
<span class="nb">print</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="n">df1</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">DataFrame</span><span class="p">(</span><span class="n">b</span><span class="p">)</span>
<span class="nb">print</span><span class="p">(</span><span class="n">df1</span><span class="p">)</span>
</pre></div>
</div>
</div>
</div>
<p>and many other operations.</p>
<p>The <strong>Series</strong> class is another important class included in
<strong>pandas</strong>. You can view it as a specialization of <strong>DataFrame</strong> but where
we have just a single column of data. It shares many of the same features as _DataFrame. As with <strong>DataFrame</strong>,
most operations are vectorized, achieving thereby a high performance when dealing with computations of arrays, in particular labeled arrays.
As we will see below it leads also to a very concice code close to the mathematical operations we may be interested in.
For multidimensional arrays, we recommend strongly <a class="reference external" href="http://xarray.pydata.org/en/stable/">xarray</a>. <strong>xarray</strong> has much of the same flexibility as <strong>pandas</strong>, but allows for the extension to higher dimensions than two.</p>
</div>
</div>
<script type="text/x-thebe-config">
{
requestKernel: true,
binderOptions: {
repo: "binder-examples/jupyter-stacks-datascience",
ref: "master",
},
codeMirrorConfig: {
theme: "abcdef",
mode: "python"
},
kernelOptions: {
kernelName: "python3",
path: "./testbook"
},
predefinedOutput: true
}
</script>
<script>kernelName = 'python3'</script>
</div>
</div>
</div>
<div class='prev-next-bottom'>
</div>
<footer class="footer mt-5 mt-md-0">
<div class="container">
<p>
By Morten Hjorth-Jensen<br/>
&copy; Copyright 2020.<br/>
</p>
</div>
</footer>
</main>
</div>
</div>
<script src="../_static/js/index.js"></script>
</body>
</html>