diff --git a/tp/derivees.ipynb b/tp/derivees.ipynb index 63e7c4174626bbef2445e87990d7b882214b2f6e..b6bbda95a036519e2c46c5449e11acd2941e6c0d 100644 --- a/tp/derivees.ipynb +++ b/tp/derivees.ipynb @@ -7,12 +7,22 @@ "[<img src=\"https://gitlab.irit.fr/toc/etu-n7/controle-optimal/-/raw/master/ressources/Logo-toulouse-inp-N7.png\" alt=\"N7\" height=\"80\"/>](https://gitlab.irit.fr/toc/etu-n7/controle-optimal)\n", "<img src=\"https://gitlab.irit.fr/toc/ens-n7/texCoursN7/-/raw/main/logo-insa.png\" alt=\"INSA\" height=\"80\" style=\"margin-left:50px\"/>\n", "\n", - "# Calcul de dérivées et équation différentielles\n", + "# Calcul de dérivées\n", "\n", - "- Date : 2023-2024\n", + "- Date : 2024-2025\n", "- Durée approximative : 1h15\n", "\n", - "## Introduction\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Introduction\n", + "</div>\n", "\n", "Il existe plusieurs façon de calculer une dérivée sur un calculateur : \n", "\n", @@ -42,6 +52,7 @@ "using ForwardDiff\n", "using LinearAlgebra\n", "using Plots\n", + "using Plots.Measures\n", "using Printf" ] }, @@ -49,9 +60,19 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Dérivées par différences finies avant\n", - "\n", - "Soit $f$ une fonction lisse de $\\mathbb{R}^{n}$ dans $\\mathbb{R}^{m}$, $x$ un point de $\\mathbb{R}^{n}$ et $v$ un vecteur de $\\mathbb{R}^{n}$. Si on note $g \\colon h \\mapsto f(x+hv)$, alors on a d'après la formule de Taylor-Young~:\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Dérivées par différences finies avant\n", + "</div>\n", + "\n", + "Soit $f$ une fonction lisse de $\\mathbb{R}^{n}$ dans $\\mathbb{R}^{m}$, $x$ un point de $\\mathbb{R}^{n}$ et $v$ un vecteur de $\\mathbb{R}^{n}$. Si on note $g \\colon h \\mapsto f(x+hv)$, alors on a d'après la formule de Taylor-Young :\n", "$$\n", " g(h) = \\sum_{i=0}^{n} \\frac{h^i}{i!} g^{(i)}(0) + R_n(h), \\quad R_n(h) = o(h^n),\n", "$$\n", @@ -75,7 +96,7 @@ "\n", "Notons $\\mathrm{num}(g,\\, h)$ la valeur de $g(h)$ calculée numériquement et supposons que l'on puisse majorer l'erreur relative numérique par : \n", "$$\n", - " \\left\\| \\mathrm{num}(g,h) - g(h) \\right\\| \\coloneqq \\| e_h\\| \\leq \\mathrm{eps}_\\mathrm{mach} L_f,\n", + " \\left\\| \\mathrm{num}(g,h) - g(h) \\right\\| := \\| e_h\\| \\leq \\mathrm{eps}_\\mathrm{mach} L_f,\n", "$$\n", "ou $L_f$ est une constante qui dépend de la valeur de $f$ sur le domaine d'intérêt. Ainsi on a : \n", "\\begin{align*}\n", @@ -102,7 +123,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Dérivées par différences finies centrées\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Dérivées par différences finies centrées\n", + "</div>\n", "\n", "On peut utiliser un schéma de différences finies centrée pour calculer la dérviée de $g$. \n", "$$\n", @@ -119,7 +150,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Dérivées par différentiation complexe\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Dérivées par différentiation complexe\n", + "</div>\n", "\n", "Les formules des schémas avant et centrée sont sensibles aux calculs de la différence $\\Delta f = f(x+h) - f(x)$ ou $\\Delta f = f(x+h) - f(x-h)$. Pour remédier à ce problème, les [différences finies à pas complexe](https://dl.acm.org/doi/10.1145/838250.838251) ont été introduites.\n", "Si on suppose que la fonction $g$ est holomorphe, c'est-à-dire dérivable au sens complexe,\n", @@ -132,12 +173,12 @@ "On considère alors l'approximation : \n", "\n", "$$\n", - " f'(x) \\cdot v = g'(0) \\approx \\frac{\\mathrm{Im}(g(x+ih))}{h}.\n", + " f'(x) \\cdot v = g'(0) \\approx \\frac{\\mathrm{Im}(f(x+ihv))}{h}.\n", "$$\n", "\n", "On peut prouver que l'approximation ci-dessus est au moins d'ordre 2 et aussi démontrer que tout pas inférieur à $h_*$ est optimal, avec \n", "$$\n", - " h_{*} \\approx \\sqrt{eps_{mach}}.\n", + " h_{*} \\approx \\sqrt{\\mathrm{eps}_{\\mathrm{mach}}}.\n", "$$\n", "\n", "**Remarque.** Utiliser en `Julia` la commande `imag` pour calculer la partie imaginaire d'un nombre complexe et la variable `im` pour représenter l'unité imaginaire." @@ -147,20 +188,30 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Dérivées par différentiation automatique via les nombres duaux\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Dérivées par différentiation automatique via les nombres duaux\n", + "</div>\n", "\n", "Les nombres duaux s'écrivent sous la forme $a + b\\, \\varepsilon$ avec $(a,b)\\in \\mathbb{R}^2$ et $\\varepsilon^2 = 0$. Nous allons voir comment nous pouvons les utiliser pour calculer des dérivées.\n", "\n", "Soit deux fonctions $f, g \\colon \\mathbb{R} \\to \\mathbb{R}$ dérivables, de dérivées respectives $f'$ et $g'$. On pose\n", "\n", "$$\n", - "f(a + b\\, \\varepsilon) \\coloneqq f(a) + f'(a)\\, b\\, \\varepsilon\n", + "f(a + b\\, \\varepsilon) := f(a) + f'(a)\\, b\\, \\varepsilon\n", "$$\n", "\n", "et\n", "\n", "$$\n", - "g(a + b\\, \\varepsilon) \\coloneqq g(a) + g'(a)\\, b\\, \\varepsilon.\n", + "g(a + b\\, \\varepsilon) := g(a) + g'(a)\\, b\\, \\varepsilon.\n", "$$\n", "\n", "On a alors automatiquement les propriétés suivantes. Posons $d = x + \\varepsilon$, alors :\n", @@ -192,7 +243,17 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Fonctions auxiliaires" + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Fonctions auxiliaires\n", + "</div>" ] }, { @@ -251,7 +312,23 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## La méthode principale pour le calcul de dérivées" + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "La méthode principale pour le calcul de dérivées\n", + "</div>\n", + "\n", + "La fonction `derivative` ci-dessous calcule la dérivée directionnelle\n", + "\n", + "$$\n", + " f'(x) \\cdot v.\n", + "$$" ] }, { @@ -285,16 +362,6 @@ "end;" ] }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Exercice 1\n", - "\n", - "1. Compléter la fonction `derivative` ci-dessus avec les méthodes de différences finies avant, centrée, par différentiation complexe et par différentiation automatique via les nombres duaux.\n", - "2. Exécuter le code ci-dessous et vérifier les résultats obtenus." - ] - }, { "cell_type": "code", "execution_count": null, @@ -322,6 +389,16 @@ "end;" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercice 1\n", + "\n", + "1. Compléter la fonction `derivative` ci-dessus avec les méthodes de différences finies avant, centrée, par différentiation complexe et par différentiation automatique via les nombres duaux.\n", + "2. Exécuter le code ci-dessous et vérifier les résultats obtenus." + ] + }, { "cell_type": "code", "execution_count": null, @@ -366,11 +443,21 @@ "cell_type": "markdown", "metadata": {}, "source": [ - "## Pas optimal\n", + "<div style=\"width:95%;\n", + " margin:10px;\n", + " padding:8px;\n", + " background-color:#afa;\n", + " border:2px solid #bbffbb;\n", + " border-radius:10px;\n", + " font-weight:bold;\n", + " font-size:1.5em;\n", + " text-align:center;\">\n", + "Pas optimal\n", + "</div>\n", "\n", "On se propose de tester pour la fonction $\\cos$ aux points $x_0=\\pi/3$, $x_1 = 10^6\\times\\pi/3$ et la fonction $\\cos+10^{-8} \\mathcal{N}(0, \\, 1)$ au point $x_0=\\pi/3$ l'erreur entre les différences finies et la dérivée au point considéré en fonction de $h$. On prendra $h=10^{-i}$ pour $i= \\{1,\\ldots,16\\}$ et on tracera ces erreurs dans une échelle logarithmique (en `Julia`, avec le package `Plots` on utilise l'option `scale=:log10`).\n", "\n", - "## Exercice 2\n", + "### Exercice 2\n", "\n", "- Visualiser les différentes erreurs en fonction de $h$ pour les différentes méthodes de calcul de dérivées. Commentaires.\n", "- Modifier la précision de $x_0$ et $x_1$ en `Float32`. Commentaires." @@ -383,21 +470,36 @@ "outputs": [], "source": [ "# affichage des erreurs en fonction de h\n", - "function print_errors(steps, errors, h_star, title)\n", + "function plot_errors(steps, errors, h_star, title)\n", "\n", + " steps_save = steps\n", + " ymax = 10^10\n", + "\n", + " # supprimer les erreurs nulles\n", " non_nul_element = findall(!iszero, errors) \n", - " errors = errors[non_nul_element];\n", - " steps = steps[non_nul_element];\n", + " errors = errors[non_nul_element]\n", + " steps = steps[non_nul_element]\n", "\n", " # Courbe des erreurs pour les differents steps en bleu\n", - " p1 = plot((10.).^(-steps), errors, xscale=:log10, yscale=:log10, linecolor=:blue, lw=2);\n", + " plt = plot((10.).^(-steps), errors, xscale=:log10, yscale=:log10, linecolor=:blue, lw=2, legend=false)\n", + "\n", + " # régler xlims pour toujours avoir tous les steps de départ\n", + " plot!(plt, xlims=(10^(-maximum(steps_save)), 10^(-minimum(steps_save))))\n", + "\n", + " # ylims toujours entre 10^-16 et ymax\n", + " plot!(plt, ylims=(10^(-16), ymax))\n", "\n", " # Ligne verticale pour situer l'erreur optimale h* en rouge\n", - " plot!(p1,[h_star, h_star], [minimum(errors), maximum(errors)], linecolor=:red)\n", - " plot!(p1, xlabel = \"h\", ylabel = \"erreurs\", title = title);\n", + " plot!(plt,[h_star, h_star], [10^(-16), ymax], linecolor=:red, lw=1, linestyle=:dash)\n", + "\n", + " # titre de la figure et xlabel\n", + " plot!(plt, xlabel = \"h\", title = title, legend=false, titlefontsize=10)\n", + "\n", + " # ajouter des marges en bas de la figure pour mieux voir le xlabel \n", + " plot!(plt, bottom_margin = 5mm)\n", "\n", " #\n", - " display(p1)\n", + " return plt\n", "\n", "end;" ] @@ -408,7 +510,7 @@ "metadata": {}, "outputs": [], "source": [ - "# Les differentes fonctions et la dérivée theorique\n", + "# Les différentes fonctions et la dérivée théorique\n", "fun1(x) = cos(x)\n", "fun2(x) = cos(x) + 1.e-8*randn()\n", "dfun(x) = -sin(x);" @@ -445,17 +547,12 @@ "end\n", "\n", "# Affichage des erreurs\n", - "print_errors(steps, err_x0, h_star, \"Erreur en x0\")\n", - "print_errors(steps, err_x0p, h_star, \"Erreur en x0 avec perturbation\")\n", - "print_errors(steps, err_x1, h_star, \"Erreur en x1\")\n" + "p1 = plot_errors(steps, err_x0, h_star, \"cos(x0)\")\n", + "p2 = plot_errors(steps, err_x0p, h_star, \"cos(x0) + perturbation\")\n", + "p3 = plot_errors(steps, err_x1, h_star, \"cos(x1)\")\n", + "\n", + "plot(p1, p2, p3, layout=(1,3), size=(850, 350))" ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [] } ], "metadata": { diff --git a/tp/install.ipynb b/tp/install.ipynb index 373ba258bc413ceb50682a3bb056806f8993df3d..65d2d21cc0d04608f8d35f3c3e99543c3ab2617d 100644 --- a/tp/install.ipynb +++ b/tp/install.ipynb @@ -35,7 +35,9 @@ " \"OrdinaryDiffEq\", \n", " \"Plots\", \n", " \"Polynomials\", \n", - " \"Printf\"])" + " \"Printf\"])\n", + "\n", + "Pkg.build(\"IJulia\")" ] }, {