Skip to content
Snippets Groups Projects
Commit 3e1624e4 authored by mcla's avatar mcla
Browse files

lab test

parent b1fabb68
Branches
No related tags found
No related merge requests found
Pipeline #17656 passed
Showing
with 3606 additions and 1 deletion
_build/
.ipynb_checkpoints
*/.ipynb_checkpoints/*
image: python:latest
# variables:
# PIP_CACHE_DIR: "$CI_PROJECT_DIR/.cache/pip"
# cache:
# paths:
# - .cache/pip
# - venv/
# before_script:
# - python -V
# lav venv miljø med venv, ikke virtualenv
# - pip install virtualenv
# - virtualenv venv
# - source venv/bin/activate
pages:
script:
- pip install -r requirements.txt
- jupyter-book build pg_cs
- mv pg_cs/_build/html/ public/
artifacts:
paths:
- public
expire_in: 4 weeks
only:
- main
LICENSE 0 → 100755
MIT License
Copyright (c) 2023, Michael Clasen Linderoth
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
init # How to create your own Course Site
\ No newline at end of file
This repository is a template for creating your own Course Site, which if you wish, can be embedded into DTU Learn or any other web service, more or less.
To get started it is useful to learn about the very few files and folders included in this template.
## Files and folders
What files are supported
reference bib file
Table of content: https://jupyterbook.org/customize/toc.html
Draft
Changing folders and structure
## Great, now what? Building the book/website
As currently configured, you basically only have to alter or add files and "commit" these changes. When doing so, the site will build and update itself, within a few minutes.
### Building the book
#### Advanced use
You know to create a basic website, then please proceed to dive into the full Jupyter Book documentation, for more advanced use cases: [Jupyter Book Documentation](https://jupyterbook.org/en/stable/intro.html)
#### Credits
This project is created using the excellent open source [Jupyter Book project](https://jupyterbook.org/) in combination with several other open source projects.
#######################################################################################
# A default configuration that will be loaded for all jupyter books
# See the documentation for help and more options:
# https://jupyterbook.org/customize/config.html
#######################################################################################
# Book settings
title : PG Course site # The title of the book. Will be placed in the left navbar.
author : DTU Compute # The author of the book
copyright : "2023" # Copyright year to be placed in the footer
logo : logo.png # A path to the book logo
# Only build table of content _toc.yml files
only_build_toc_files: true
# Information about where the book exists on the web
repository:
url: https://github.com/mclacompute/pgcoursesite # Online location of your book
path_to_book: /pg_cs # Optional path to your book, relative to the repository root
branch: main # Which branch of the repository should be used when creating links (optional)
# Add GitHub buttons to your book
# See https://jupyterbook.org/customize/config.html#add-a-link-to-your-repository
html:
use_issues_button: true
use_repository_button: true
launch_buttons:
notebook_interface: "classic" # or "jupyterlab"
# binderhub_url: "https://mybinder.org"
colab_url: "https://colab.research.google.com"
# thebe : true # husk jupyterlite
parse:
myst_enable_extensions:
- amsmath
- colon_fence
# - deflist
- dollarmath
# - html_admonition
# - html_image
- linkify
# - replacements
# - smartquotes
- substitution
- tasklist
myst_url_schemes: [mailto, http, https] # URI schemes that will be recognised as external URLs in Markdown links
myst_dmath_double_inline: true # Allow display math ($$) within an inline context
# Force re-execution of notebooks on each build.
# See https://jupyterbook.org/content/execute.html
# execute:
# execute_notebooks: force
# Add a bibtex file so that we can create citations
bibtex_bibfiles:
- references.bib
# Define the name of the latex output file for PDF builds
# latex:
# latex_documents:
# targetname: book.tex
# Table of contents
# Learn more at https://jupyterbook.org/customize/toc.html
format: jb-book
root: intro
parts:
- caption:
chapters:
- file: democontent/demopage
sections:
- file: democontent/notebooks
- file: democontent/Intro-SymPy
# - file: democontent/...
- caption:
chapters:
- file: weeks/weeklyplan
sections:
- file: weeks/week1
- file: weeks/week2
- file: weeks/week3
- file: weeks/week4
# sections:
# - file: longday
# sections:
# - file: exl1
# - file: exl2
# - file: shortday
# sections:
# - file: exs1
# - file: exs2
- caption:
chapters:
- file: enotes/enotes
This diff is collapsed.
%% Cell type:markdown id: tags:
# Differentialligningssystemer
Demo af Christian Mikkelstrup og Hans Henrik Hermansen
%% Cell type:code id: tags:
``` python
from sympy import *
init_printing(use_latex='mathjax')
```
%% Cell type:markdown id: tags:
## Homogene systemer af første ordens lineære diff-ligninger
## 1. Systemmatricen har to reelle egenværdier
Givet differentialligningsystemet
\begin{gather*}
\frac{\text{d}}{\text{d}t}x_1(t) = 5x_1(t) - 3x_2(t)\\
\frac{\text{d}}{\text{d}t}x_2(t) = 6x_1(t) - 4x_2(t)
\end{gather*}
%% Cell type:markdown id: tags:
### a. Simuleret håndregning via diagonaliseringsmetoden
Først løser vi systemet i hånden vha. diagonaliseringsmetoden, dvs. vi opstiller og analyserer systemmatricen
%% Cell type:code id: tags:
``` python
t,C1,C2 = symbols("t C1:3")
A = Matrix([[5,-3],[6,-4]])
ev = A.eigenvects()
res = C1 * E ** (ev[0][0]*t) * ev[0][2][0] + C2 * E ** (ev[1][0]*t) * ev[1][2][0]
res
```
%% Cell type:markdown id: tags:
### b. via dsolve
Vi kan også finde løsningen direkte med dsolve
%% Cell type:code id: tags:
``` python
x1 = Function("x1")
x2 = Function("x2")
eq1 = Eq(diff(x1(t),t),5 * x1(t) - 3 * x2(t))
eq2 = Eq(diff(x2(t),t),6*x1(t) - 4*x2(t))
dsolve([eq1, eq2])
```
%% Cell type:markdown id: tags:
## 2. Systemmatricen har to komplekse egenværdier
Givet differentialligningssystemet
\begin{gather*}
\frac{\text{d}}{\text{d}t}x_1(t) = 2x_1(t) + 2x_2(t)\\
\frac{\text{d}}{\text{d}t}x_2(t) = -x_1(t) + 4x_2(t)
\end{gather*}
%% Cell type:markdown id: tags:
## a. Simuleret håndregning
Fremgangsmåden her er den samme.
%% Cell type:code id: tags:
``` python
A = Matrix([[2,2],[-1,4]])
ev = A.eigenvects()
res = C1 * E ** (ev[0][0]*t) * ev[0][2][0] + C2 * E ** (ev[1][0]*t) * ev[1][2][0]
res
```
%% Cell type:markdown id: tags:
Nu finder vi også den fuldstændige reelle løsning vha. metode 17.5
%% Cell type:code id: tags:
``` python
a = re(ev[0][0])
b = im(ev[0][0])
re_ev = re(ev[0][2][0])
im_ev = im(ev[0][2][0])
u1 = E ** (a * t) * (cos(b * t) * re_ev - sin(b * t) * im_ev)
u2 = E ** (a * t) * (sin(b * t) * re_ev + cos(b * t) * im_ev)
C1 * u1 + C2 * u2
```
%% Cell type:markdown id: tags:
### b. Med dsovle
%% Cell type:code id: tags:
``` python
eq1 = Eq(diff(x1(t),t),2*x1(t) + 2*x2(t))
eq2 = Eq(diff(x2(t),t),-x1(t) + 4*x2(t))
dsolve([eq1, eq2])
```
%% Cell type:markdown id: tags:
Selvom løsningerne ser lidt forskellige ud, så er de lig hinanden.
%% Cell type:markdown id: tags:
## 3. Betinget løsning med plot
Lad os se på systemet fra eksempel 1 igen.
\begin{gather*}
\frac{\text{d}}{\text{d}t}x_1(t) = 5x_1(t) - 3x_2(t)\\
\frac{\text{d}}{\text{d}t}x_2(t) = 6x_2(t) - 4x_2(t)
\end{gather*}
Vi kom frem til den fuldstændige løsning
\begin{gather*}
\begin{bmatrix} x_1(t) \\ x_2(t) \end{bmatrix} = C_1 e^{-t} \begin{bmatrix}1 \\ 2\end{bmatrix} + C_2 e^{2t} \begin{bmatrix} 1 \\ 1 \end{bmatrix}
\end{gather*}
Lad os finde et $C_1$ og $C_2$, der medfører at $x_1(0) = 2$ og $x_2(0) = 3$.
%% Cell type:markdown id: tags:
### a. Simuleret håndregning
Først finder vi lige løsningen igen
%% Cell type:code id: tags:
``` python
t,C1,C2 = symbols("t C1:3")
A = Matrix([[5,-3],[6,-4]])
ev = A.eigenvects()
fuld = C1 * E ** (ev[0][0]*t) * ev[0][2][0] + C2 * E ** (ev[1][0]*t) * ev[1][2][0]
x1_fuld, x2_fuld = fuld[0],fuld[1]
x1_fuld, x2_fuld
```
%% Cell type:markdown id: tags:
Nu kan løse for $c_1$ og $c_2$
%% Cell type:code id: tags:
``` python
solve([Eq(x1_fuld.subs(t,0),2),Eq(x2_fuld.subs(t,0),3)])
```
%% Cell type:markdown id: tags:
Vi kunne også gøre dette med $\text{dsolve}$
%% Cell type:code id: tags:
``` python
eq1 = Eq(diff(x1(t),t),5 * x1(t) - 3 * x2(t))
eq2 = Eq(diff(x2(t),t),2*x1(t) - 4*x2(t))
dsolve([eq1, eq2],ics={x1(0) : 2, x2(0) : 3})
```
%% Cell type:markdown id: tags:
Nu, hvor vi har fundet $c_1$ og $c_2$, kan vi plotte vores løsning.
%% Cell type:code id: tags:
``` python
plot(x1_fuld.subs([(C1,2),(C2,1)]),x2_fuld.subs([(C1,2),(C2,1)]),xlim=(-1,1),ylim=(0,8),legend=True)
```
%% Cell type:markdown id: tags:
# Partielle afledede, Gradienter, Retningsafledede
Demo af Christian Mikkelstrup og Hans Henrik Hermansen
%% Cell type:code id: tags:
``` python
from sympy import *
from dtumathtools import *
from IPython import get_ipython
%matplotlib widget
init_printing()
```
%% Cell type:markdown id: tags:
Velkommen tilbage efter jul og januar, og velkommen til foråret i mat1. Der kommer til at være en helt masse nyt pensum, og blandt andet en helt masse 3D-plots! Til dette har vi udviklet ``dtumathtools``, som vil følge jer i løbet af foråret. Den indeholder ``dtuplot`` som skal bruges til at plotte, samt flere gode hjælpefunktioner. Det kan hentes fra terminalen, hvor man så skal skrive ``pip install dtumathtools`` (tilsvarende med ``pip3``). Det tager op til ~5 minutter før den er helt færdig og tillader dig igen at skrive i terminalen. Efter dette kan resten af demoen nydes.
%% Cell type:markdown id: tags:
## Partielt afledte ved brug af ``diff``
I dag introducerer vi partielle afledte, samt hvordan vi kan benytte dem. For at vise hvordan man kan få de partielt afledte, kan vi kigge på funktionen
%% Cell type:code id: tags:
``` python
x, y = symbols('x y')
f = x*y**2+x
f
```
%% Cell type:markdown id: tags:
og finde de afledte med kommandoen som vi også brugte sidste semester
%% Cell type:code id: tags:
``` python
f.diff(x), f.diff(y)
```
%% Cell type:markdown id: tags:
På samme måde kan man finde de afledte *af anden orden*
%% Cell type:code id: tags:
``` python
f.diff(x,2), f.diff(y,2), f.diff(x,y), f.diff(y,x)
```
%% Cell type:markdown id: tags:
Vi kan så indsætte værdier i denne, for eksempel $\frac{\partial}{\partial x}f(x,y)$ taget i $(-2,3)$ ved
%% Cell type:code id: tags:
``` python
f.diff(x).subs({x:-2,y:3})
```
%% Cell type:markdown id: tags:
Eller $\frac{\partial}{\partial x\partial y}f(x,y)$, taget i $(5,-13)$ ved
%% Cell type:code id: tags:
``` python
f.diff(x,y).subs({x:5,y:-13})
```
%% Cell type:markdown id: tags:
## Grafer og niveaukurver
Vi skal nu, for første gang til at plotte funktioner af flere variable, og altså i 3D! Her er et valg man skal tage, for man har nemlig mulighed for at rotere et plot rundt, så man kan se det fra flere vinkler.
Hvis man ikke gør noget aktivt (eller hvis man bruger kommandoen ``%matplotlib inline``), kommer plots som I er vant til fra efteråret (som også kommer med hvis man eksporterer til pdf),
%% Cell type:code id: tags:
``` python
f = 4-x**2-y**2
p=dtuplot.plot3d(f, (x,-3,3),(y,-3,3))
```
%% Cell type:markdown id: tags:
Ovenstående kommando laver plottet som en **statisk** PNG-fil, hvilket er smart hvis man skal printe Notebook'en eller eksportere til PDF. Hvis man i stedet kører ``%matplotlib qt`` (i den følgende blok udkommenteret, men prøv at fjerne udkommenteringen \#), aktiverer man **interaktive** plots. Alle efterfølgende plots "popper" nu ud af VS Code, hvorefter man man rotere plottet rundt og se det fra flere vinkler! Prøv derefter at plotte 3D plottet igen!
%% Cell type:code id: tags:
``` python
# %matplotlib widget
```
%% Cell type:markdown id: tags:
### Om interaktive plots
%% Cell type:markdown id: tags:
Bemærk: `%matplotlib qt` virker normalt kun hvis man kører fx VS Code på egen laptop. Hvis man fx kører Python på en online server i browseren som Google Colab, vil `%matplotlib qt` ikke virke. Her kan man prøve widgets i stedet for: `%matplotlib ipympl`. Det kører at man lige installerer pakken `ipympl`. Samlet oversigt:
%% Cell type:code id: tags:
``` python
# Fjern udkommentering for den backend der ønskes brugt
# %matplotlib inline # statisk plots
# %matplotlib qt # QT (cute) interaktivt pop-ud plots
# %matplotlib ipympl # Widget/ipynpl interaktivt inline plots (ikke så stabil som QT og kan kræve restart af kernel)
# %matplotlib --list # liste over alle backends
```
%% Cell type:markdown id: tags:
Vi kan også plotte højdelinjer, altså et 2D plot over en 3D struktur ved:
%% Cell type:code id: tags:
``` python
dtuplot.plot_contour(f, (x,-3,3),(y,-3,3), is_filled=False)
```
%% Cell type:markdown id: tags:
Og hvis vi vil bestemme hvilke højder der vises, kan vi bruge,
%% Cell type:code id: tags:
``` python
zvals = [-2,-1,0,1]
dtuplot.plot_contour(f, (x,-3,3),(y,-3,3), rendering_kw={"levels":zvals, "alpha":0.5}, is_filled=False)
```
%% Cell type:markdown id: tags:
I ovenstående plot er der brugt ``rendering_kw={....}`` som argument, og det kan se lidt underligt ud. Dette er blot hvilke æstetiske (rendering) indstillinger der skal bruges, eksempelvis ``color``, ``alpha``, osv. Man kan også i det fleste tilfælde "bare" skrive ``{....}``, og så ved den godt at det er det æstetiske, men det er mere tydeligt at skrive det med.
Her er samme plot vist, nu med højder som farver, i 3D,
%% Cell type:code id: tags:
``` python
p=dtuplot.plot3d(f, (x,-3,3),(y,-3,3), use_cm=True, legend=True)
```
%% Cell type:markdown id: tags:
## Gradientvektorfelter
Vi kigger nu på vektorfeltet
\begin{equation}
f(x,y)=\cos(x)+\sin(y).
\end{equation}
Gradienten for $f$ taget i punktet $(x,y)$ er en vektor, som har symbolet $\nabla f(x,y)$ ($\nabla$ kaldes *nabla*). Den er sammensat af de to partielt afledte,
%% Cell type:code id: tags:
``` python
f = cos(x)+sin(y)
nf = Matrix([f.diff(x), f.diff(y)])
nf
```
%% Cell type:markdown id: tags:
Som let plottes ved,
%% Cell type:code id: tags:
``` python
dtuplot.plot_vector(nf, (x,-pi/2,3/2*pi),(y,0,2*pi),scalar=False)
```
%% Cell type:markdown id: tags:
Eller hvis det skal være lidt flottere (her er ``rendering_kw`` splittet, så man kan specificere for pile og contours seperat),
%% Cell type:code id: tags:
``` python
dtuplot.plot_vector(nf, (x,-pi/2,3/2*pi),(y,0,2*pi),
quiver_kw={"color":"black"},
contour_kw={"cmap": "Blues_r", "levels": 20},
grid=False, xlabel="x", ylabel="y",n=15)
```
%% Cell type:markdown id: tags:
Som i 3D visualiseres ved
%% Cell type:code id: tags:
``` python
# "camera" Juster hvorfra man skal se på grafen
# meget brugbart, hvis man vil have bestemt
# rotation med i pdf-filen
p = dtuplot.plot3d(f, (x,-pi/2,3/2*pi),(y,0,2*pi),use_cm=True, camera={"elev":45, "azim":-65}, legend=True)
```
%% Cell type:markdown id: tags:
# Retningsafledt af funktion af to variable
Vi betragter funktionen
%% Cell type:code id: tags:
``` python
f = 1-x**2/2-y**2/2
f
```
%% Cell type:markdown id: tags:
Vi ønsker nu den retningsafledte af $f$ fra punktet $(1,-1)$ i retningen givet ved enhedsvektoren,
%% Cell type:code id: tags:
``` python
x0 = Matrix([1,-1])
e = Matrix([-1,-2]).normalized()
e, N(e)
```
%% Cell type:code id: tags:
``` python
p1 = dtuplot.scatter(x0, rendering_kw={"markersize":10,"color":'r'}, xlim=[-2,2],ylim=[-2,2],show=False)
p1.extend(dtuplot.quiver(x0,e,show=False))
p1.show()
```
%% Cell type:markdown id: tags:
Vi får gradienten i punktet $x_0$ ved
%% Cell type:code id: tags:
``` python
Nabla = Matrix([diff(f,x),diff(f,y)]).subs({x:x0[0],y:x0[1]})
Nabla
```
%% Cell type:markdown id: tags:
Hvorefter den retningsafledte, $f'((1,-1), e)$, findes ved
%% Cell type:code id: tags:
``` python
a = e.dot(Nabla)
a
```
%% Cell type:markdown id: tags:
Dette viser, at *f aftager* fra punktet $(1,-1)$ i retningen $e$. Dette er fordi den retningsafledte angiver raten, hvormed $f$ aftager.
%% Cell type:markdown id: tags:
# Parameterkurve i (x,y)-planen og dens tangenter
Vi betragter spiralen, givet ved parameterfremstillingen,
%% Cell type:code id: tags:
``` python
u, t = symbols('u t', real=True)
r = Matrix([u*cos(u), u*sin(u)])
r
```
%% Cell type:markdown id: tags:
Tangentvektoren i et vilkårligt punkt fåes nu til
%% Cell type:code id: tags:
``` python
rd = diff(r,u)
rd
```
%% Cell type:markdown id: tags:
Vi finder nu en parameterfremstilling for tangenten til spiralen i røringspunktet $((0,-\frac{3\pi}{2}))$, svarende til parameterværdien $u_0=\frac{3\pi}{2}$, som ses ved,
%% Cell type:code id: tags:
``` python
u0 = 3*pi/2
rdu0 = rd.subs(u,u0)
ru0 = r.subs(u,u0)
ru0
```
%% Cell type:markdown id: tags:
Parameterfremstillingen for tangenten i $u_0$ findes ved
%% Cell type:code id: tags:
``` python
T = ru0 + t*rdu0
T
```
%% Cell type:markdown id: tags:
Det hele kan nu visualiseres ved
%% Cell type:code id: tags:
``` python
p = dtuplot.plot_parametric(r[0], r[1],(u,0,4*pi),rendering_kw={"color":"red"},use_cm=False,show=False)
p.extend(dtuplot.plot_parametric(T[0],T[1],(t,-1.5,1.5),rendering_kw={"color":"royalblue"},use_cm=False,show=False))
p.extend(dtuplot.scatter(ru0,rendering_kw={"markersize":10,"color":'black'}, show=False))
p.extend(dtuplot.quiver(ru0,rdu0,rendering_kw={"color":"black"},show=False))
p.show()
```
%% Cell type:code id: tags:
``` python
```
This diff is collapsed.
# PG demo Content
## Question 1
````{card}
A smooth function $f$ of one variable fulfills that $\,f(2)=1\,$ and $\,f'(2)=1\,.$ Its approximating second-degree polynomial with development point $\,x_0=2\,$ fulfills $\,P_2(1)=1\,.$ Determine $\,P_2(x)\,$.
````
```{admonition} Hint for question
:class: dropdown
In this exercise we are testing in particular the following differentiation rules:
- The product rule used when differentiating the product of two functions.
- The chain rule used when differentiating a composite function ("a function within a function").
\begin{gather*}
a_1=b_1+c_1\\
a_2=b_2+c_2-d_2+e_2
\end{gather*}
```
```{admonition} Answer
:class: tip, dropdown
$$
\int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
$$
```
We will compute the volume of the parallelepiped that is spanned by three geometric vectors in a standard coordinate system in 3D space
:::{important}
Remember to readTheorem 10.54 in eNote 10.
:::
## Question 2
````{card}
A smooth function $f$ of one variable fulfills that $\,f(2)=1\,$ and $\,f'(2)=1\,.$ Its approximating second-degree polynomial with development point $\,x_0=2\,$ fulfills $\,P_2(1)=1\,.$ Determine $\,P_2(x)\,$.
````
```{admonition} Hint for question
:class: dropdown
In this exercise we are testing in particular the following differentiation rules:
- The product rule used when differentiating the product of two functions.
- The chain rule used when differentiating a composite function ("a function within a function").
\begin{gather*}
a_1=b_1+c_1\\
a_2=b_2+c_2-d_2+e_2
\end{gather*}
```
```{admonition} Answer
:class: tip, dropdown
$$
\int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
$$
```
---
jupytext:
cell_metadata_filter: -all
formats: md:myst
text_representation:
extension: .md
format_name: myst
format_version: 0.13
jupytext_version: 1.11.5
kernelspec:
display_name: Python 3
language: python
name: python3
---
# Notebooks with MyST Markdown
Jupyter Book also lets you write text-based notebooks using MyST Markdown.
See [the Notebooks with MyST Markdown documentation](https://jupyterbook.org/file-types/myst-notebooks.html) for more detailed instructions.
This page shows off a notebook written in MyST Markdown.
## An example cell
With MyST Markdown, you can define code cells with a directive like so:
```{code-cell}
print(2 + 2)
```
```{code-cell}
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
data = np.random.randn(2, 100)
fig, ax = plt.subplots()
ax.scatter(*data, c=data[1], s=100*np.abs(data[0]));
```
When your book is built, the contents of any `{code-cell}` blocks will be
executed with your default Jupyter kernel, and their outputs will be displayed
in-line with the rest of your content.
```{seealso}
Jupyter Book uses [Jupytext](https://jupytext.readthedocs.io/en/latest/) to convert text-based files to notebooks, and can support [many other text-based notebook files](https://jupyterbook.org/file-types/jupytext.html).
```
## Create a notebook with MyST Markdown
MyST Markdown notebooks are defined by two things:
1. YAML metadata that is needed to understand if / how it should convert text files to notebooks (including information about the kernel needed).
See the YAML at the top of this page for example.
2. The presence of `{code-cell}` directives, which will be executed with your book.
That's all that is needed to get started!
## Quickly add YAML metadata for MyST Notebooks
If you have a markdown file and you'd like to quickly add YAML metadata to it, so that Jupyter Book will treat it as a MyST Markdown Notebook, run the following command:
```
jupyter-book myst init path/to/markdownfile.md
```
# Markdown Files
Whether you write your book's content in Jupyter Notebooks (`.ipynb`) or
in regular markdown files (`.md`), you'll write in the same flavor of markdown
called **MyST Markdown**.
This is a simple file to help you get started and show off some syntax.
## What is MyST?
MyST stands for "Markedly Structured Text". It
is a slight variation on a flavor of markdown called "CommonMark" markdown,
with small syntax extensions to allow you to write **roles** and **directives**
in the Sphinx ecosystem.
%% Cell type:markdown id:bc47e68d tags:
(myst-content/math)=
# Math and equations
Jupyter Book uses [MathJax](http://docs.mathjax.org/) for typesetting math in your HTML book build.
This allows you to have LaTeX-style mathematics in your online content.
This page shows you a few ways to control this.
:::{seealso}
For more information about equation numbering,
see the [MathJax equation numbering documentation](http://docs.mathjax.org/en/v2.7-latest/tex.html#automatic-equation-numbering).
:::
:::{tip}
By default MathJax version 2 is currently used.
If you are using a lot of math, you may want to try using version 3, which claims to improve load speeds by 60 - 80%:
```yaml
sphinx:
config:
mathjax_path: https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js
```
See the [Sphinx documentation](sphinx:sphinx.ext.mathjax) for details.
:::
## In-line math
To insert in-line math use the `$` symbol within a Markdown cell.
For example, the text `$this_{is}^{inline}$` will produce: $this_{is}^{inline}$.
%% Cell type:markdown id:fb8cd4ec tags:
## Math blocks
You can also include math blocks for separate equations. This allows you to focus attention
on more complex or longer equations, as well as link to them in your pages. To use a block
equation, wrap the equation in either `$$` or `\begin` statements.
For example,
```latex
$$
\int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
$$
```
results in:
$$
\int_0^\infty \frac{x^3}{e^x-1}\,dx = \frac{\pi^4}{15}
$$
%% Cell type:markdown id:a8f88cc6 tags:
(math:latex)=
### Latex-style math
You can enable parsing LaTeX-style math blocks with the `amsmath` MyST extension. Enable it by adding the following to `_config.yml`
```yaml
parse:
myst_enable_extensions:
# don't forget to list any other extensions you want enabled,
# including those that are enabled by default!
- amsmath
```
Once enabled, you can define math blocks like so:
```latex
\begin{gather*}
a_1=b_1+c_1\\
a_2=b_2+c_2-d_2+e_2
\end{gather*}
\begin{align}
a_{11}& =b_{11}&
a_{12}& =b_{12}\\
a_{21}& =b_{21}&
a_{22}& =b_{22}+c_{22}
\end{align}
```
which results in:
\begin{gather*}
a_1=b_1+c_1\\
a_2=b_2+c_2-d_2+e_2
\end{gather*}
\begin{align}
a_{11}& =b_{11}&
a_{12}& =b_{12}\\
a_{21}& =b_{21}&
a_{22}& =b_{22}+c_{22}
\end{align}
:::{seealso}
The MyST guides to [dollar math syntax](myst-parser:syntax/math), [LaTeX math syntax](myst-parser:syntax/amsmath), and [how MyST-Parser works with MathJax](myst-parser:syntax/mathjax).
For advanced use, also see how to [define MathJax TeX Macros](sphinx/tex-macros).
:::
%% Cell type:markdown id:b2e67170 tags:
### Numbering equations
If you'd like to number equations so that you can refer to them later, use the **math directive**.
It looks like this:
````md
```{math}
:label: my_label
my_math
```
````
For example, the following code:
````md
```{math}
:label: my_label
w_{t+1} = (1 + r_{t+1}) s(w_t) + y_{t+1}
```
````
will generate
```{math}
:label: my_label
w_{t+1} = (1 + r_{t+1}) s(w_t) + y_{t+1}
```
Alternatively you can use the dollar math syntax with a prefixed label:
```md
$$
w_{t+1} = (1 + r_{t+1}) s(w_t) + y_{t+1}
$$ (my_other_label)
```
which generates
$$
w_{t+1} = (1 + r_{t+1}) s(w_t) + y_{t+1}
$$ (my_other_label)
:::{note}
Labels cannot start with an integer, or they won't be able to be referenced and
will throw a warning message if referenced. For example, `:label: 1` and `:label: 1eq` cannot
be referenced.
:::
### Linking to equations
If you have created an equation with a label, you can link to it from within your text
(and across pages!).
You can refer to the equation using the label that you've provided by using
the `{eq}` role. For example:
```md
- A link to an equation directive: {eq}`my_label`
- A link to a dollar math block: {eq}`my_other_label`
```
results in
- A link to an equation directive: {eq}`my_label`
- A link to a dollar math block: {eq}`my_other_label`
:::{note}
`\labels` inside LaTeX environment are not currently identified, and so cannot be referenced.
We hope to implement this in a future update (see [executablebooks/MyST-Parser#202](https://github.com/executablebooks/MyST-Parser/issues/202))!
:::
Source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:markdown id:6e94e772 tags:
# Min overskrift
%% Cell type:markdown id:a32ec2c9 tags:
\begin{gather*}
\frac{\text{d}}{\text{d}t}x_1(t) = 5x_1(t) - 3x_2(t)\\
\frac{\text{d}}{\text{d}t}x_2(t) = 6x_1(t) - 4x_2(t)
\end{gather*}
# exl1
# exl2
# exs1
# exs2
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment