From 31981a7612a6cf641536050113a7008d6df3823a Mon Sep 17 00:00:00 2001 From: Meik Hellmund Date: Tue, 14 May 2024 13:20:00 +0200 Subject: [PATCH] removed nb dir from git tracking --- nb/10_Strings.ipynb | 981 -------------- nb/5_TricksHelp.ipynb | 335 ----- nb/6_ArraysEtcP1.ipynb | 755 ----------- nb/7_ArraysP2.ipynb | 2054 ------------------------------ nb/9_functs.ipynb | 1136 ----------------- nb/Erste_Bsp.ipynb | 341 ----- nb/Pi.ipynb | 233 ---- nb/Pi2.ipynb | 313 ----- nb/ablaufsteuerung.ipynb | 83 -- nb/entwicklungsumgebungen.ipynb | 167 --- nb/example.ipynb | 146 --- nb/first_contact.ipynb | 628 --------- nb/first_contact.nbconvert.ipynb | 493 ------- nb/intro.ipynb | 114 -- nb/makie.ipynb | 77 -- nb/numerictypes.ipynb | 1296 ------------------- nb/pcomplex.ipynb | 989 -------------- nb/script1.sh | 8 - nb/summary.ipynb | 167 --- nb/syntax.ipynb | 1185 ----------------- nb/types.ipynb | 1497 ---------------------- 21 files changed, 12998 deletions(-) delete mode 100644 nb/10_Strings.ipynb delete mode 100644 nb/5_TricksHelp.ipynb delete mode 100644 nb/6_ArraysEtcP1.ipynb delete mode 100644 nb/7_ArraysP2.ipynb delete mode 100644 nb/9_functs.ipynb delete mode 100644 nb/Erste_Bsp.ipynb delete mode 100644 nb/Pi.ipynb delete mode 100644 nb/Pi2.ipynb delete mode 100644 nb/ablaufsteuerung.ipynb delete mode 100644 nb/entwicklungsumgebungen.ipynb delete mode 100644 nb/example.ipynb delete mode 100644 nb/first_contact.ipynb delete mode 100644 nb/first_contact.nbconvert.ipynb delete mode 100644 nb/intro.ipynb delete mode 100644 nb/makie.ipynb delete mode 100644 nb/numerictypes.ipynb delete mode 100644 nb/pcomplex.ipynb delete mode 100755 nb/script1.sh delete mode 100644 nb/summary.ipynb delete mode 100644 nb/syntax.ipynb delete mode 100644 nb/types.ipynb diff --git a/nb/10_Strings.ipynb b/nb/10_Strings.ipynb deleted file mode 100644 index b850542..0000000 --- a/nb/10_Strings.ipynb +++ /dev/null @@ -1,981 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "7c21d452", - "metadata": {}, - "source": [ - "# Zeichen, Strings und Unicode\n", - "\n", - "## Zeichencodierungen (Frühgeschichte)\n", - "\n", - "Es gab - abhängig von Hersteller, Land, Programmiersprache, Betriebsssystem,... - eine große Vielzahl von Codierungen. \n", - "\n", - "Bis heute relevant sind:\n", - "\n", - "\n", - "### ASCII \n", - "Der _American Standard Code for Information Interchange_ wurde 1963 in den USA als Standard veröffentlicht. \n", - "\n", - "- Er definiert $2^7=128$ Zeichen, und zwar: \n", - " - 33 Steuerzeichen, wie `newline`, `escape`, `end of transmission/file`, `delete`\n", - " - 95 graphisch darstellbare Zeichen:\n", - " - 52 lateinische Buchstaben `a-z, A-Z`\n", - " - 10 Ziffern `0-9`\n", - " - 7 Satzzeichen `.,:;?!\"`\n", - " - 1 Leerzeichen ` `\n", - " - 6 Klammern `[{()}]`\n", - " - 7 mathematische Operationen `+-*/<>=`\n", - " - 12 Sonderzeichen ``` #$%&'\\^_|~`@ ``` \n", - "\n", - "- ASCII ist heute noch der \"kleinste gemeinsame Nenner\" im Codierungs-Chaos.\n", - "- Die ersten 128 Unicode-Zeichen sind identisch mit ASCII.\n", - "\n", - "### ISO 8859-Zeichensätze\n", - "\n", - "- ASCII nutzt nur 7 Bits. \n", - "- In einem Byte kann man durch Setzen des 8. Bits weitere 128 Zeichen unterbringen. \n", - "- 1987/88 wurden im ISO 8859-Standard verschiedene 1-Byte-Codierungen festgelegt, die alle ASCII-kompatibel sind, darunter:\n", - "\n", - ":::{.narrow}\n", - " |Codierung | Region | Sprachen|\n", - " |:-----------|:----------|:-------|\n", - " |ISO 8859-1 (Latin-1) | Westeuropa | Deutsch, Französisch,...,Isländisch\n", - " |ISO 8859-2 (Latin-2) | Osteuropa | slawische Sprachen mit lateinischer Schrift\n", - " |ISO 8859-3 (Latin-3) | Südeuropa | Türkisch, Maltesisch,...\n", - " |ISO 8859-4 (Latin-4) | Nordeuropa | Estnisch, Lettisch, Litauisch, Grönländisch, Sami\n", - " |ISO 8859-5 (Latin/Cyrillic) | Osteuropa | slawische Sprachen mit kyrillischer Schrift\n", - " |ISO 8859-6 (Latin/Arabic) | |\n", - " |ISO 8859-7 (Latin/Greek) | |\n", - " |...| | \n", - " |ISO 8859-15 (Latin-9)| | 1999: Revision von Latin-1: jetzt mit Euro-Zeichen! \n", - " \n", - ":::\n", - " \n", - "## Unicode \n", - "\n", - "Das Ziel des Unicode-Consortiums ist eine einheitliche Codierung für alle Schriften der Welt.\n", - "\n", - "- Unicode Version 1 erschien 1991\n", - "- Unicode Version 15 erschien 2021 mit 149 186 Zeichen (das sind 4489 mehr als Unicode 14), darunter: \n", - " - 161 Schriften \n", - " - mathematische und technische Symbole\n", - " - Emojis und andere Symbole, Steuer- und Formatierungszeichen\n", - "- davon entfallen über 90 000 Zeichen auf die CJK-Schriften (Chinesisch/Japanisch/Koreanisch) \n", - " \n", - " \n", - "### Technische Details\n", - "\n", - "- Jedem Zeichen wird ein `codepoint` zugeordnet. Das ist einfach eine fortlaufende Nummer.\n", - "- Diese Nummer wird hexadezimal notiert\n", - " - entweder 4-stellig als `U+XXXX` (0-te Ebene) \n", - " - oder 5...6-stellig als `U+XXXXXX` (weitere Ebenen)\n", - "- Jede Ebene geht von `U+XY0000` bis `U+XYFFFF`, kann also $2^{16}=65\\;534$ Zeichen enthalten. \n", - "- Vorgesehen sind bisher 17 Ebenen `XY=00` bis `XY=10`, also der Wertebereich von `U+0000` bis `U+10FFFF`.\n", - "- Damit sind maximal 21 Bits pro Zeichen nötig.\n", - "- Die Gesamtzahl der damit möglichen Codepoints ist etwas kleiner als 0x10FFFF, da aus technischen Gründen gewisse Bereiche nicht verwendet werden. Sie beträgt etwa 1.1 Millionen, es ist also noch viel Platz. \n", - "- Bisher wurden nur Codepoints aus den Ebenen \n", - " - Ebene 0 = BMP _Basic Multilingual Plane_ `U+0000 - U+FFFF`,\n", - " - Ebene 1 = SMP _Supplementary Multilingual Plane_ `U+010000 - U+01FFFF`,\n", - " - Ebene 2 = SIP _Supplementary Ideographic Plane_ `U+020000 - U+02FFFF`, \n", - " - Ebene 3 = TIP _Tertiary Ideographic Plane_ `U+030000 - U+03FFFF` und\n", - " - Ebene 14 = SSP _Supplementary Special-purpose Plane_ `U+0E0000 - U+0EFFFF` vergeben.\n", - "- `U+0000` bis `U+007F` ist identisch mit ASCII\n", - "- `U+0000` bis `U+00FF` ist identisch mit ISO 8859-1 (Latin-1)\n", - "\n", - "### Eigenschaften von Unicode-Zeichen\n", - "\n", - "Im Standard wird jedes Zeichen beschrieben duch\n", - "\n", - " - seinen Codepoint (Nummer) \n", - " - einen Namen (welcher nur aus ASCII-Großbuchstaben, Ziffern und Minuszeichen besteht) und \n", - " - verschiedene Attributen wie\n", - " - Laufrichtung der Schrift \n", - " - Kategorie: Großbuchstabe, Kleinbuchstabe, modifizierender Buchstabe, Ziffer, Satzzeichen, Symbol, Seperator,....\n", - "\n", - "Im Unicode-Standard sieht das dann so aus (zur Vereinfachung nur Codepoint und Name):\n", - "```\n", - "...\n", - "U+0041 LATIN CAPITAL LETTER A\n", - "U+0042 LATIN CAPITAL LETTER B\n", - "U+0043 LATIN CAPITAL LETTER C\n", - "U+0044 LATIN CAPITAL LETTER D\n", - "...\n", - "U+00E9 LATIN SMALL LETTER E WITH ACUTE\n", - "U+00EA LATIN SMALL LETTER E WITH CIRCUMFLEX\n", - "...\n", - "U+0641 ARABIC LETTER FEH\n", - "U+0642 ARABIC LETTER QAF\n", - "...\n", - "U+21B4 RIGHTWARDS ARROW WITH CORNER DOWNWARDS\n", - "...\n", - "```\n", - "\n", - "Wie sieht 'RIGHTWARDS ARROW WITH CORNER DOWNWARDS' aus?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "48697b80", - "metadata": {}, - "outputs": [], - "source": [ - "'\\U21b4'" - ] - }, - { - "cell_type": "markdown", - "id": "568c932d", - "metadata": {}, - "source": [ - "### Eine Auswahl an Schriften \n", - "\n", - "::: {.content-visible when-format=\"html\"}\n", - "\n", - ":::{.callout-note}\n", - "Falls im Folgenden einzelne Zeichen oder Schriften in Ihrem Browser nicht darstellbar sind, müssen Sie geeignete \n", - "Fonts auf Ihrem Rechner installieren. \n", - "\n", - "Alternativ können Sie die PDF-Version dieser Seite verwenden. Dort sind alle Fonts eingebunden.\n", - ":::\n", - "\n", - ":::\n", - "\n", - "Eine kleine Hilfsfunktion:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "44eecb07", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - "printuc(c, n):\n", - "print n characters from unicode table, starting with character c \n", - "\"\"\"\n", - "function printuc(c, n)\n", - " for i in 0:n-1\n", - " print(c + i)\n", - " end\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "9857ec8a", - "metadata": {}, - "source": [ - "__Kyrillisch__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d1827fb6", - "metadata": {}, - "outputs": [], - "source": [ - "printuc('\\U0400', 100)" - ] - }, - { - "cell_type": "markdown", - "id": "1975b4c8", - "metadata": {}, - "source": [ - "__Tamilisch__\n", - "\n", - ":::{.cellmerge}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0ac169a1", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: true\n", - "#| output: false\n", - "printuc('\\U0be7',20)" - ] - }, - { - "cell_type": "markdown", - "id": "cf47c3ec", - "metadata": {}, - "source": [ - "\\begingroup\\setmonofont{Noto Sans Tamil}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4c539418", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: false\n", - "#| output: true\n", - "printuc('\\U0be7',20)" - ] - }, - { - "cell_type": "markdown", - "id": "57b1dd19", - "metadata": {}, - "source": [ - "\\endgroup\n", - "\n", - ":::\n", - "\n", - "__Schach__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6d474a65", - "metadata": {}, - "outputs": [], - "source": [ - "printuc('\\U2654', 12)" - ] - }, - { - "cell_type": "markdown", - "id": "9c31ea8a", - "metadata": {}, - "source": [ - "__Mathematische Operatoren__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "58aaf4c5", - "metadata": {}, - "outputs": [], - "source": [ - "printuc('\\U2200', 255)" - ] - }, - { - "cell_type": "markdown", - "id": "9b6c63b0", - "metadata": {}, - "source": [ - "__Runen__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "88859f95", - "metadata": {}, - "outputs": [], - "source": [ - "printuc('\\U16a0', 40)" - ] - }, - { - "cell_type": "markdown", - "id": "08203fd6", - "metadata": {}, - "source": [ - ":::{.cellmerge}\n", - "\n", - "__Scheibe (Diskus) von Phaistos__\n", - "\n", - "- Diese Schrift ist nicht entziffert. \n", - "- Es ist unklar, welche Sprache dargestellt wird.\n", - "- Es gibt nur ein einziges Dokument in dieser Schrift: die Tonscheibe von Phaistos aus der Bronzezeit \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "640c2422", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: true\n", - "#| output: false\n", - "printuc('\\U101D0', 46 )" - ] - }, - { - "cell_type": "markdown", - "id": "ee56718c", - "metadata": {}, - "source": [ - "\\begingroup\\setmonofont{Phaistos.otf}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0a728045", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: false\n", - "#| output: true\n", - "printuc('\\U101D0', 46 )" - ] - }, - { - "cell_type": "markdown", - "id": "cfcb78f6", - "metadata": {}, - "source": [ - "\\endgroup\n", - "\n", - ":::\n", - "\n", - "### Unicode transformation formats: UTF-8, UTF-16, UTF-32\n", - "\n", - "_Unicode transformation formats_ legen fest, wie eine Folge von Codepoints als eine Folge von Bytes dargestellt wird. \n", - "\n", - "Da die Codepoints unterschiedlich lang sind, kann man sie nicht einfach hintereinander schreiben. Wo hört einer auf und fängt der nächste an? \n", - "\n", - "- __UTF-32__: Das einfachste, aber auch speicheraufwändigste, ist, sie alle auf gleiche Länge zu bringen. Jeder Codepoint wird in 4 Bytes = 32 Bit kodiert. \n", - "- Bei __UTF-16__ wird ein Codepoint entweder mit 2 Bytes oder mit 4 Bytes dargestellt. \n", - "- Bei __UTF-8__ wird ein Codepoint mit 1,2,3 oder 4 Bytes dargestellt. \n", - "- __UTF-8__ ist das Format mit der höchsten Verbreitung. Es wird auch von Julia verwendet. \n", - "\n", - "\n", - "### UTF-8\n", - "\n", - "- Für jeden Codepoint werden 1, 2, 3 oder 4 volle Bytes verwendet. \n", - "\n", - "- Bei einer Codierung mit variabler Länge muss man erkennen können, welche Bytefolgen zusammengehören:\n", - " - Ein Byte der Form 0xxxxxxx steht für einen ASCII-Codepoint der Länge 1.\n", - " - Ein Byte der Form 110xxxxx startet einen 2-Byte-Code.\n", - " - Ein Byte der Form 1110xxxx startet einen 3-Byte-Code.\n", - " - Ein Byte der Form 11110xxx startet einen 4-Byte-Code.\n", - " - Alle weiteren Bytes eines 2-,3- oder 4-Byte-Codes haben die Form 10xxxxxx. \n", - "\n", - "- Damit ist der Platz, der für den Codepoint zur Verfügung steht (Anzahl der x):\n", - " - Ein-Byte-Code: 7 Bits\n", - " - Zwei-Byte-Code: 5 + 6 = 11 Bits\n", - " - Drei-Byte-Code: 4 + 6 + 6 = 16 Bits\n", - " - Vier-Byte-Code: 3 + 6 + 6 + 6 = 21 Bits\n", - "\n", - "- Damit ist jeder ASCII-Text automatisch auch ein korrekt codierter UTF-8-Text.\n", - "\n", - "- Sollten die bisher für Unicode festgelegten 17 Ebenen = 21 Bit = 1.1 Mill. mögliche Zeichen mal erweitert werden, dann wird UTF-8 auf 5- und 6-Byte-Codes erweitert. \n", - " \n", - "\n", - "## Zeichen und Zeichenketten in Julia\n", - "\n", - "### Zeichen: `Char` \n", - "\n", - "Der Datentyp `Char` kodiert ein einzelnes Unicode-Zeichen. \n", - "\n", - "- Julia verwendet dafür einfache Anführungszeichen: `'a'`. \n", - "- Ein `Char` belegt 4 Bytes Speicher und \n", - "- repräsentiert einen Unicode-Codepoint.\n", - "- `Char`s können von/zu `UInt`s umgewandelt werden und \n", - "- der Integer-Wert ist gleich dem Unicode-codepoint.\n", - "\n", - "\n", - "### Zeichenketten: `String`\n", - "\n", - "- Für Strings verwendet Julia doppelte Anführungszeichen: `\"a\"`.\n", - "- Sie sind UTF-8-codiert, d.h., ein Zeichen kann zwischen 1 und 4 Bytes lang sein.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "707c245e", - "metadata": {}, - "outputs": [], - "source": [ - "@show typeof('a') sizeof('a') typeof(\"a\") sizeof(\"a\");" - ] - }, - { - "cell_type": "markdown", - "id": "ce463383", - "metadata": {}, - "source": [ - "- `Char`s können von/zu `UInt`s umgewandelt werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6488fdf6", - "metadata": {}, - "outputs": [], - "source": [ - "UInt('a')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2637de2b", - "metadata": {}, - "outputs": [], - "source": [ - "b = Char(0x2656)" - ] - }, - { - "cell_type": "markdown", - "id": "985adab7", - "metadata": {}, - "source": [ - "__Bei einem Nicht-ASCII-String unterscheiden sich Anzahl der Bytes und Anzahl der Zeichen:__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "53c741c8", - "metadata": {}, - "outputs": [], - "source": [ - "asciistr = \"Hello World!\"\n", - "@show length(asciistr) ncodeunits(asciistr);" - ] - }, - { - "cell_type": "markdown", - "id": "bf536c2d", - "metadata": {}, - "source": [ - "(Das Leerzeichen zählt natürlich auch.)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "37e36e85", - "metadata": {}, - "outputs": [], - "source": [ - "str = \"😄 Hellö 🎶\"\n", - "@show length(str) ncodeunits(str);" - ] - }, - { - "cell_type": "markdown", - "id": "b9caf74d", - "metadata": {}, - "source": [ - "__Iteration über einen String iteriert über die Zeichen:__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0e8e04e3", - "metadata": {}, - "outputs": [], - "source": [ - "for i in str\n", - " println(i, \" \", typeof(i))\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "ce0cfd1b", - "metadata": {}, - "source": [ - "### Verkettung von Strings\n", - "\n", - "\"Strings mit Verkettung bilden ein nichtkommutatives Monoid.\"\n", - "\n", - "Deshalb wird in Julia die Verkettung multiplikativ geschrieben.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6f35d90f", - "metadata": {}, - "outputs": [], - "source": [ - " str * asciistr * str" - ] - }, - { - "cell_type": "markdown", - "id": "898a6ea1", - "metadata": {}, - "source": [ - "Damit sind auch Potenzen mit natürlichem Exponenten definiert.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cb9d7217", - "metadata": {}, - "outputs": [], - "source": [ - "str^3, str^0" - ] - }, - { - "cell_type": "markdown", - "id": "cc89a9ca", - "metadata": {}, - "source": [ - "### Stringinterpolation\n", - "\n", - "Das Dollarzeichen hat in Strings eine Sonderfunktion, die wir schon oft in \n", - "`print()`-Anweisungen genutzt haben. MAn kann damit eine Variable oder einen Ausdruck interpolieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "16b8af0a", - "metadata": {}, - "outputs": [], - "source": [ - "a = 33.4\n", - "b = \"x\"\n", - "\n", - "s = \"Das Ergebnis für $b ist gleich $a und die verdoppelte Wurzel daraus ist $(2sqrt(a))\\n\"" - ] - }, - { - "cell_type": "markdown", - "id": "1ddcc1ad", - "metadata": {}, - "source": [ - "### Backslash escape sequences \n", - "\n", - "Der _backslash_ `\\` hat in Stringkonstanten ebenfalls eine Sonderfunktion. \n", - "Julia benutzt die von C und anderen Sprachen bekannten _backslash_-Codierungen für Sonderzeichen und für Dollarzeichen und Backslash selbst:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "64a50bab", - "metadata": {}, - "outputs": [], - "source": [ - "s = \"So bekommt man \\'Anführungszeichen\\\" und ein \\$-Zeichen und einen\\nZeilenumbruch und ein \\\\ usw... \"\n", - "print(s)" - ] - }, - { - "cell_type": "markdown", - "id": "f8a758f6", - "metadata": {}, - "source": [ - "### Triple-Quotes\n", - "\n", - "Man kann Strings auch mit Triple-Quotes begrenzen. \n", - "In dieser Form bleiben Zeilenumbrüche und Anführungszeichen erhalten:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a042c5ed", - "metadata": {}, - "outputs": [], - "source": [ - "s = \"\"\"\n", - " Das soll\n", - "ein \"längerer\" \n", - " 'Text' sein.\n", - "\"\"\"\n", - "\n", - "print(s)" - ] - }, - { - "cell_type": "markdown", - "id": "7ff4c2dd", - "metadata": {}, - "source": [ - "### Raw strings\n", - "\n", - "In einem `raw string` sind alle backslash-Codierungen außer `\\\"` abgeschaltet:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "929529cf", - "metadata": {}, - "outputs": [], - "source": [ - "s = raw\"Ein $ und ein \\ und zwei \\\\ und ein 'bla'...\"\n", - "print(s)" - ] - }, - { - "cell_type": "markdown", - "id": "0040e4d6", - "metadata": {}, - "source": [ - "## Weitere Funktionen für Zeichen und Strings (Auswahl)\n", - "\n", - "### Tests für Zeichen\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "195a2a3e", - "metadata": {}, - "outputs": [], - "source": [ - "@show isdigit('0') isletter('Ψ') isascii('\\U2655') islowercase('α') \n", - "@show isnumeric('½') iscntrl('\\n') ispunct(';');" - ] - }, - { - "cell_type": "markdown", - "id": "2e50dae6", - "metadata": {}, - "source": [ - "### Anwendung auf Strings\n", - "\n", - "Diese Tests lassen sich z.B. mit `all()`, `any()` oder `count()` auf Strings anwenden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c778a4ad", - "metadata": {}, - "outputs": [], - "source": [ - "all(ispunct, \";.:\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6a162d83", - "metadata": {}, - "outputs": [], - "source": [ - "any(isdigit, \"Es ist 3 Uhr! 🕒\" )" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c2d57533", - "metadata": {}, - "outputs": [], - "source": [ - "count(islowercase, \"Hello, du!!\")" - ] - }, - { - "cell_type": "markdown", - "id": "f6562800", - "metadata": {}, - "source": [ - "### Weitere String-Funktionen\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "495799ef", - "metadata": {}, - "outputs": [], - "source": [ - "@show startswith(\"Lampenschirm\", \"Lamp\") occursin(\"pensch\", \"Lampenschirm\") \n", - "@show endswith(\"Lampenschirm\", \"irm\"); " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "13e4d303", - "metadata": {}, - "outputs": [], - "source": [ - "@show uppercase(\"Eis\") lowercase(\"Eis\") titlecase(\"eiSen\");" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "36451c74", - "metadata": {}, - "outputs": [], - "source": [ - "# remove newline from end of string\n", - "\n", - "@show chomp(\"Eis\\n\") chomp(\"Eis\");" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a665d380", - "metadata": {}, - "outputs": [], - "source": [ - "split(\"π ist irrational.\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "64967f02", - "metadata": {}, - "outputs": [], - "source": [ - "replace(\"π ist irrational.\", \"ist\" => \"ist angeblich\")" - ] - }, - { - "cell_type": "markdown", - "id": "663832cf", - "metadata": {}, - "source": [ - "## Indizierung von Strings\n", - "\n", - "Strings sind nicht mutierbar aber indizierbar. Dabei gibt es ein paar Besonderheiten.\n", - "\n", - "- Der Index nummeriert die Bytes des Strings. \n", - "- Bei einem nicht-ASCII-String sind nicht alle Indizes gültig, denn\n", - "- ein gültiger Index adressiert immer ein Unicode-Zeichen.\n", - "\n", - "Unser Beispielstring:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "23d51f20", - "metadata": {}, - "outputs": [], - "source": [ - "str" - ] - }, - { - "cell_type": "markdown", - "id": "639c88fa", - "metadata": {}, - "source": [ - "Das erste Zeichen\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "68ba5cb6", - "metadata": {}, - "outputs": [], - "source": [ - "str[1]" - ] - }, - { - "cell_type": "markdown", - "id": "44617a04", - "metadata": {}, - "source": [ - "Dieses Zeichen ist in UTF8-Kodierung 4 Bytes lang. Damit sind 2,3 und 4 ungültige Indizes. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c4575cca", - "metadata": {}, - "outputs": [], - "source": [ - "str[2]" - ] - }, - { - "cell_type": "markdown", - "id": "e558202c", - "metadata": {}, - "source": [ - "Erst das 5. Byte ist ein neues Zeichen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3813bbdf", - "metadata": {}, - "outputs": [], - "source": [ - "str[5]" - ] - }, - { - "cell_type": "markdown", - "id": "48f4cca9", - "metadata": {}, - "source": [ - "Auch bei der Adressierung von Substrings müssen Anfang und Ende jeweils gültige Indizes sein, d.h., der Endindex muss ebenfalls das erste Byte eines Zeichens indizieren und dieses Zeichen ist das letzte des Teilstrings. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "546d4ed2", - "metadata": {}, - "outputs": [], - "source": [ - "str[1:7]" - ] - }, - { - "cell_type": "markdown", - "id": "1007a717", - "metadata": {}, - "source": [ - "Die Funktion `eachindex()` liefert einen Iterator über die gültigen Indizes:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d01e440e", - "metadata": {}, - "outputs": [], - "source": [ - "for i in eachindex(str)\n", - " c = str[i]\n", - " println(\"$i: $c\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "2f35e6bf", - "metadata": {}, - "source": [ - "Wie üblich macht collect() aus einem Iterator einen Vektor.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b1644ea5", - "metadata": {}, - "outputs": [], - "source": [ - "collect(eachindex(str))" - ] - }, - { - "cell_type": "markdown", - "id": "dc77d9e5", - "metadata": {}, - "source": [ - "Die Funktion `nextind()` liefert den nächsten gültigen Index.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5c9f35e7", - "metadata": {}, - "outputs": [], - "source": [ - "@show nextind(str, 1) nextind(str, 2); " - ] - }, - { - "cell_type": "markdown", - "id": "6d1e346b", - "metadata": {}, - "source": [ - "Warum verwendet Julia einen Byte-Index und keinen Zeichenindex? Der Hauptgrund dürfte die Effizienz der Indizierung sein.\n", - "\n", - "- In einem langen String, z.B. einem Buchtext, ist die Stelle `s[123455]` mit einem Byte-Index schnell zu finden. \n", - "- Ein Zeichen-Index müsste in der UTF-8-Codierung den ganzen String durchlaufen, um das n-te Zeichen zu finden, da die Zeichen 1,2,3 oder 4 Bytes lang sein können.\n", - "\n", - "\n", - "Einige Funktionen liefern Indizes oder Ranges als Resultat. Sie liefern immer gültige Indizes:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e1ec4807", - "metadata": {}, - "outputs": [], - "source": [ - "findfirst('l', str)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2f8520fd", - "metadata": {}, - "outputs": [], - "source": [ - "findfirst(\"Hel\", str)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0f07cff3", - "metadata": {}, - "outputs": [], - "source": [ - "str2 = \"αβγδϵ\"^3" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "19e5bcc4", - "metadata": {}, - "outputs": [], - "source": [ - "n = findfirst('γ', str2)" - ] - }, - { - "cell_type": "markdown", - "id": "f614e688", - "metadata": {}, - "source": [ - "So kann man ab dem nächsten nach `n=5` gültigen Index weitersuchen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3f3b90b4", - "metadata": {}, - "outputs": [], - "source": [ - "findnext('γ', str2, nextind(str2, n))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/5_TricksHelp.ipynb b/nb/5_TricksHelp.ipynb deleted file mode 100644 index bbbbd7b..0000000 --- a/nb/5_TricksHelp.ipynb +++ /dev/null @@ -1,335 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "32301000", - "metadata": {}, - "source": [ - "# Arbeit mit Julia: REPL, Pakete, Introspection\n", - "\n", - "\n", - "\n", - "## Dokumentation\n", - "\n", - "Die offizielle Julia-Dokumentation [https://docs.julialang.org/](https://docs.julialang.org/) enthält zahlreiche Übersichten, darunter:\n", - "\n", - " - [https://docs.julialang.org/en/v1/base/punctuation/](https://docs.julialang.org/en/v1/base/punctuation/) Verzeichnis der Symbole\n", - " - [https://docs.julialang.org/en/v1/manual/unicode-input/](https://docs.julialang.org/en/v1/manual/unicode-input/) Verzeichnis spezieller Unicode-Symbole und deren Eingabe in Julia via Tab-Vervollständigung\n", - " - [https://docs.julialang.org/en/v1/manual/mathematical-operations/#Rounding-functions](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Rounding-functions) Liste mathematischer Funktionen \n", - "\n", - "\n", - "\n", - "\n", - "## Julia REPL (Read - Eval - Print - Loop)\n", - "\n", - "Nach dem Start von Julia in einem Terminal kann man neben Julia-Code auch verschiedene Kommandos eingeben \n", - "\n", - ":::{.narrow}\n", - "| Kommando | Wirkung |\n", - "| :----------------------------| :------------------------ |\n", - "| `exit()` oder `Ctrl-d` | exit Julia |\n", - "| `Ctrl-c` | interrupt |\n", - "| `Ctrl-l` | clear screen |\n", - "| Kommando mit `;` beenden | Ausgabe unterdrückt |\n", - "| `include(\"filename.jl\")` | Datei mit Julia-Code einlesen und ausführen |\n", - "\n", - "\n", - "\n", - "Der REPL hat verschiedene Modi: \n", - "\n", - "| Modus | Prompt | Modus starten | Modus verlassen |\n", - "| :- | :- | :- | :- |\n", - "| default| `julia>` | | `Ctrl-d`|\n", - "| Package manager | `pkg>` | `]` | `backspace` |\n", - "| Help | `help?>` | `?`| `backspace `|\n", - "|Shell | `shell>` | `;` | `backspace`|\n", - "\n", - ":::\n", - "\n", - "\n", - "## Jupyter-Notebooks (IJulia)\n", - "\n", - "\n", - "In einem Jupyter-Notebook sind die Modi sind als Einzeiler in einer eigenen Input-Zelle nutzbar: \n", - "\n", - "(i) ein Kommando des Paket-Managers:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "efacde4f", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "] status " - ] - }, - { - "cell_type": "markdown", - "id": "85fec425", - "metadata": {}, - "source": [ - "(ii) eine Help-Abfrage:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "80535b76", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "?sin" - ] - }, - { - "cell_type": "markdown", - "id": "581aae68", - "metadata": {}, - "source": [ - "(iii) Ein Shell-Kommando:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c2438155", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - ";ls " - ] - }, - { - "cell_type": "markdown", - "id": "bd2c64b7", - "metadata": {}, - "source": [ - "## Der Paketmanager\n", - "\n", - "Wichtiger Teil des _Julia Ecosystems_ sind die zahlreichen Pakete, die Julia erweitern.\n", - "\n", - "- Einige Pakete sind Teil jeder Julia-Installation und müssen nur mit einer `using Paketname`-Anweisung aktiviert werden. \n", - " - Sie bilden die sogenannte _Standard Library_ und dazu gehören \n", - " - `LinearAlgebra`, `Statistics`, `SparseArrays`, `Printf`, `Pkg` und andere.\n", - "- Über 9000 Pakete sind offiziell registriert, siehe [https://julialang.org/packages/](https://julialang.org/packages/). \n", - " - Diese können mit wenigen Tastendrücken heruntergeladen und installiert werden.\n", - " - Dazu dient der _package manager_ `Pkg`.\n", - " - Man kann ihn auf zwei Arten verwenden: \n", - " - als normale Julia-Anweisungen, die auch in einer `.jl`-Programmdatei stehen können:\n", - " ```\n", - " using Pkg\n", - " Pkg.add(\"PaketXY\")\n", - " ```\n", - " - im speziellen pkg-Modus des Julia-REPLs:\n", - " ```\n", - " ] add PaketXY\n", - " ```\n", - " - Anschließend kann das Paket mit `using PaketXY` verwendet werden.\n", - "- Man kann auch Pakete aus anderen Quellen und selbstgeschriebene Pakete installieren.\n", - "\n", - " \n", - "### Einige Funktionen des Paketmanagers\n", - "\n", - "| Funktion | `pkg` - Mode | Erklärung |\n", - "|:------------------------|:--------------------------| :-------------------------------------------------------|\n", - "| `Pkg.add(\"MyPack\")` | `pkg> add MyPack` | add `MyPack.jl` to current environment |\n", - "| `Pkg.rm(\"MyPack\")` | `pkg> remove MyPack` | remove `MyPack.jl` from current environment |\n", - "| `Pkg.update()` | `pkg> update` | update packages in current environment |\n", - "| `Pkg.activate(\"mydir\")` | `pkg> activate mydir` | activate directory as current environment |\n", - "| `Pkg.status()` | `pkg> status` | list packages |\n", - "| `Pkg.instantiate()` | `pg> instantiate` | install all packages according to `Project.toml` |\n", - "\n", - "\n", - "### Installierte Pakete und Environments \n", - "\n", - "- Julia und der Paketmanager verwalten \n", - " 1. eine Liste der mit dem Kommando `Pkg.add()` bzw. `]add` explizit installierten Pakete mit genauer Versionsbezeichnung in einer Datei `Project.toml` und \n", - " 2. eine Liste aller dabei auch als implizite Abhängigkeiten installierten Pakete in der Datei `Manifest.toml`. \n", - "- Das Verzeichnis, in dem diese Dateien stehen, ist das `environment` und wird mit `Pkg.status()` bzw. `]status` angezeigt. \n", - "- Im Normalfall sieht das so aus: \n", - "\n", - "```\n", - "(@v1.8) pkg> status\n", - " Status `~/.julia/environments/v1.8/Project.toml`\n", - " [1dea7af3] OrdinaryDiffEq v6.7.1\n", - " [91a5bcdd] Plots v1.27.1\n", - " [438e738f] PyCall v1.93.1\n", - "```\n", - "\n", - "- Man kann für verschiedene Projekte eigene `environments` benutzen. Dazu kann man entweder Julia mit \n", - "```shell\n", - "julia --project=path/to/myproject\n", - "```\n", - "starten oder in Julia das environment mit `Pkg.activate(\"path/to/myproject\")` aktivieren. Dann werden `Project.toml, Manifest.toml` dort angelegt und verwaltet. (Die Installation der Paketdateien erfolgt weiterhin irgendwo unter `$HOME/.julia`) \n", - "\n", - "\n", - "### Zum Installieren von Paketen auf unserem Jupyter-Server `misun103`:\n", - "\n", - "- Es gibt ein zentrales Repository, in dem alle in diesem Kurs erwähnten Pakete bereits installiert sind. \n", - "- Dort haben Sie keine Schreibrechte.\n", - "- Sie können aber zusätzliche Pakete in Ihrem `HOME` installieren. Dazu ist als erster Befehl nötig, das aktuelle Verzeichnis zu aktivieren: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "87138f78", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "] activate ." - ] - }, - { - "cell_type": "markdown", - "id": "da9c6bb6", - "metadata": {}, - "source": [ - "(Man beachte den Punkt!)\n", - "\n", - "\n", - "Danach können Sie mit `add` im Pkg-Modus auch Pakete installieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7a9e6ab0", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "] add PaketXY" - ] - }, - { - "cell_type": "markdown", - "id": "d5fc8aef", - "metadata": {}, - "source": [ - "Achtung! Das kann dauern! Viele Pakete haben komplexe Abhängigkeiten und lösen die Installation von weiteren Paketen aus. Viele Pakete werden beim Installieren vorkompiliert. Im REPL sieht man den Installationsfortschritt, im Jupyter-Notebook leider nicht.\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## Der Julia JIT _(just in time)_ Compiler: Introspection\n", - "\n", - "Julia baut auf die Werkzeuge des _LLVM Compiler Infrastructure Projects_ auf.\n", - "\n", - ":::{.narrow}\n", - "Stages of Compilation \n", - "\n", - "| stage & result | introspection command |\n", - "| :--- | :--- |\n", - "|Parse $\\Longrightarrow$ Abstract Syntax Tree (AST) | `Meta.parse()` |\n", - "| Lowering: transform AST $\\Longrightarrow$ Static Single Assignment (SSA) form | `@code_lowered`|\n", - "| Type Inference | `@code_warntype`, `@code_typed` |\n", - "| Generate LLVM intermediate representation | `@code_llvm`|\n", - "| Generate native machine code | `@code_native` |\n", - "\n", - ":::\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bc5fdcec", - "metadata": {}, - "outputs": [], - "source": [ - "function f(x,y)\n", - " z = x^2 + log(y)\n", - " return 2z\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bb56b5a6", - "metadata": {}, - "outputs": [], - "source": [ - "p = Meta.parse( \"function f(x,y); z=x^2+log(y); return 2x; end \")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9a8825dd", - "metadata": {}, - "outputs": [], - "source": [ - "using TreeView\n", - "\n", - "walk_tree(p)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "aa2d2ada", - "metadata": {}, - "outputs": [], - "source": [ - "@code_lowered f(2,4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e6303b02", - "metadata": {}, - "outputs": [], - "source": [ - "@code_warntype f(2,4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "05f5a0cd", - "metadata": {}, - "outputs": [], - "source": [ - "@code_typed f(2,4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "523e86a5", - "metadata": {}, - "outputs": [], - "source": [ - "@code_llvm f(2,4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "953d5e83", - "metadata": {}, - "outputs": [], - "source": [ - "@code_native f(2,4)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/6_ArraysEtcP1.ipynb b/nb/6_ArraysEtcP1.ipynb deleted file mode 100644 index 6d27411..0000000 --- a/nb/6_ArraysEtcP1.ipynb +++ /dev/null @@ -1,755 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "81cc02aa", - "metadata": {}, - "source": [ - "# Container\n", - "\n", - "\n", - "Julia bietet eine große Auswahl von Containertypen mit weitgehend ähnlichem Interface an. \n", - "Wir stellen hier `Tuple`, `Range` und `Dict` vor, im nächsten Kapitel dann `Array`, `Vector` und `Matrix`. \n", - "\n", - "Diese Container sind: \n", - "\n", - "- **iterierbar:** Man kann über die Elemente des Containers iterieren: \n", - "```julia \n", - "for x ∈ container ... end\n", - "```\n", - "- **indizierbar:** Man kann auf Elemente über ihren Index zugreifen: \n", - "```julia\n", - "x = container[i]\n", - "``` \n", - "und einige sind auch \n", - "\n", - "- **mutierbar**: Man kann Elemente hinzufügen, entfernen und ändern.\n", - "\n", - "Weiterhin gibt es eine Reihe gemeinsamer Funktionen, z.B.\n", - "\n", - "- `length(container)` --- Anzahl der Elemente\n", - "- `eltype(container)` --- Typ der Elemente\n", - "- `isempty(container)` --- Test, ob Container leer ist\n", - "- `empty!(container)` --- leert Container (nur wenn mutierbar)\n", - "\n", - "\n", - "## Tupeln\n", - "\n", - "Ein Tupel ist ein nicht mutierbarer Container von Elementen. Es ist also nicht möglich, neue Elemente dazuzufügen oder den Wert eines Elements zu ändern. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ec893f0b", - "metadata": {}, - "outputs": [], - "source": [ - "t = (33, 4.5, \"Hello\")\n", - "\n", - "@show t[2] # indizierbar\n", - "\n", - "for i ∈ t println(i) end # iterierbar" - ] - }, - { - "cell_type": "markdown", - "id": "21549769", - "metadata": {}, - "source": [ - "Ein Tupel ist ein **inhomogener** Typ. Jedes Element hat seinen eigenen Typ und das zeigt sich auch im Typ des Tupels:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5add8abb", - "metadata": {}, - "outputs": [], - "source": [ - "typeof(t)" - ] - }, - { - "cell_type": "markdown", - "id": "e8bc972e", - "metadata": {}, - "source": [ - "Man verwendet Tupel gerne als Rückgabewerte von Funktionen, um mehr als ein Objekt zurückzulieferen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "85b3f1fd", - "metadata": {}, - "outputs": [], - "source": [ - "# Ganzzahldivision und Rest: \n", - "# Quotient und Rest werden den Variablen q und r zugewiesen\n", - "\n", - "q, r = divrem(71, 6)\n", - "@show q r;" - ] - }, - { - "cell_type": "markdown", - "id": "d144679d", - "metadata": {}, - "source": [ - "Wie man hier sieht, kann man in bestimmten Konstrukten die Klammern auch weglassen.\n", - "Dieses *implict tuple packing/unpacking* verwendet man auch gerne in Mehrfachzuweisungen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2ef18811", - "metadata": {}, - "outputs": [], - "source": [ - "x, y, z = 12, 17, 203" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "759e8783", - "metadata": {}, - "outputs": [], - "source": [ - "y" - ] - }, - { - "cell_type": "markdown", - "id": "2bed8606", - "metadata": {}, - "source": [ - "Manche Funktionen bestehen auf Tupeln als Argument oder geben immer Tupeln zurück. Dann braucht man manchmal ein Tupel aus einem Element. \n", - "\n", - "Das notiert man so:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e985c23d", - "metadata": {}, - "outputs": [], - "source": [ - "x = (13,) # ein 1-Element-Tupel" - ] - }, - { - "cell_type": "markdown", - "id": "174aed3a", - "metadata": {}, - "source": [ - "Das Komma - und nicht die Klammern -- macht das Tupel. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8359e689", - "metadata": {}, - "outputs": [], - "source": [ - "x= (13) # kein Tupel" - ] - }, - { - "cell_type": "markdown", - "id": "a5fb2b62", - "metadata": {}, - "source": [ - "## Ranges\n", - "\n", - "Wir haben *range*-Objekte schon in numerischen `for`-Schleifen verwendet.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ba823baf", - "metadata": {}, - "outputs": [], - "source": [ - "r = 1:1000\n", - "typeof(r)" - ] - }, - { - "cell_type": "markdown", - "id": "6dd2ebf4", - "metadata": {}, - "source": [ - "Es gibt verschiedene *range*-Typen. Wie man sieht, sind es über den Zahlentyp parametrisierte Typen und `UnitRange` ist z.B. ein *range* mit der Schrittweite 1. Ihre Konstruktoren heißen in der Regel `range()`. \n", - "\n", - "Der Doppelpunkt ist eine spezielle Syntax. \n", - "\n", - "- `a:b` wird vom Parser umgesetzt zu `range(a, b)` \n", - "- `a:b:c` wird umgesetzt zu `range(a, c, step=b)`\n", - "\n", - "\n", - "*Ranges* sind offensichtlich iterierbar, nicht mutierbar aber indizierbar.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5ee0a9ef", - "metadata": {}, - "outputs": [], - "source": [ - "(3:100)[20] # das zwanzigste Element" - ] - }, - { - "cell_type": "markdown", - "id": "f4524b63", - "metadata": {}, - "source": [ - "Wir erinnern an die Semantik der `for`-Schleife: `for i in 1:1000` heißt **nicht**:\n", - "\n", - "- 'Die Schleifenvariable `i` wird bei jedem Durchlauf um eins erhöht' **sondern** \n", - "- 'Der Schleifenvariable werden nacheinander die Werte 1,2,3,...,1000 aus dem Container zugewiesen'. \n", - "\n", - "Allerdings wäre es sehr ineffektiv, diesen Container tatsächlich explizit anzulegen. \n", - "\n", - "- _Ranges_ sind \"lazy\" Vektoren, die nie wirklich irgendwo als konkrete Liste abgespeichert werden. Das macht sie als Iteratoren in `for`-Schleifen so nützlich: speichersparend und schnell.\n", - "- Sie sind 'Rezepte' oder Generatoren, die auf die Abfrage 'Gib mir dein nächstes Element!' antworten.\n", - "- Tatsächlich ist der Muttertyp `AbstractRange` ein Subtyp von `AbstractVector`.\n", - "\n", - "Das Macro `@allocated` gibt aus, wieviel Bytes an Speicher bei der Auswertung eines Ausdrucks alloziert wurden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7049d454", - "metadata": {}, - "outputs": [], - "source": [ - "@allocated [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dbc66a57", - "metadata": {}, - "outputs": [], - "source": [ - "@allocated 1:20" - ] - }, - { - "cell_type": "markdown", - "id": "3d98f5f4", - "metadata": {}, - "source": [ - "Zum Umwandeln in einen 'richtigen' Vektor dient die Funktion `collect()`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fe033c47", - "metadata": {}, - "outputs": [], - "source": [ - "collect(20:-3:1)" - ] - }, - { - "cell_type": "markdown", - "id": "a94e5258", - "metadata": {}, - "source": [ - "Recht nützlich, z.B. beim Vorbereiten von Daten zum Plotten, ist der *range*-Typ `LinRange`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e4b40085", - "metadata": {}, - "outputs": [], - "source": [ - "LinRange(2, 50, 300)" - ] - }, - { - "cell_type": "markdown", - "id": "bde8b38f", - "metadata": {}, - "source": [ - "`LinRange(start, stop, n)` erzeugt eine äquidistante Liste von `n` Werten von denen der erste und der letzte die vorgegebenen Grenzen sind. \n", - "Mit `collect()` kann man bei Bedarf auch daraus den entsprechenden Vektor gewinnen.\n", - "\n", - "\n", - "## Dictionaries \n", - "\n", - "- _Dictionaries_ (deutsch: \"assoziative Liste\" oder \"Zuordnungstabelle\" oder ...) sind spezielle Container. \n", - "- Einträge in einem Vektor `v` sind durch einen Index 1,2,3.... addressierbar: `v[i]`\n", - "- Einträge in einem _dictionary_ sind durch allgemeinere _keys_ addressierbar. \n", - "- Ein _dictionary_ ist eine Ansammlung von _key-value_-Paaren.\n", - "- Damit haben _dictionaries_ in Julia den parametrisierten Typ `Dict{S,T}`, wobei `S` der Typ der _keys_ und `T` der Typ der _values_ ist\n", - "\n", - "\n", - "Man kann sie explizit anlegen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "25c7aefc", - "metadata": {}, - "outputs": [], - "source": [ - "# Einwohner 2020 in Millionen, Quelle: wikipedia\n", - "\n", - "EW = Dict(\"Berlin\" => 3.66, \"Hamburg\" => 1.85, \n", - " \"München\" => 1.49, \"Köln\" => 1.08)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9620f365", - "metadata": {}, - "outputs": [], - "source": [ - "typeof(EW)" - ] - }, - { - "cell_type": "markdown", - "id": "d3b4d2af", - "metadata": {}, - "source": [ - "und mit den _keys_ indizieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "62938a1b", - "metadata": {}, - "outputs": [], - "source": [ - "EW[\"Berlin\"]" - ] - }, - { - "cell_type": "markdown", - "id": "73ddf61d", - "metadata": {}, - "source": [ - "Das Abfragen eines nicht existierenden _keys_ ist natürlich ein Fehler.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6e16eb41", - "metadata": {}, - "outputs": [], - "source": [ - "EW[\"Leipzig\"]" - ] - }, - { - "cell_type": "markdown", - "id": "49a6d001", - "metadata": {}, - "source": [ - "Man kann ja auch vorher mal anfragen...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e43aec5d", - "metadata": {}, - "outputs": [], - "source": [ - "haskey(EW, \"Leipzig\")" - ] - }, - { - "cell_type": "markdown", - "id": "a1cefaa1", - "metadata": {}, - "source": [ - "... oder die Funktion `get(dict, key, default)` benutzen, die bei nicht existierendem Key keinen Fehler wirft sondern das 3. Argument zurückgibt. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e31c792c", - "metadata": {}, - "outputs": [], - "source": [ - "@show get(EW, \"Leipzig\", -1) get(EW, \"Berlin\", -1);" - ] - }, - { - "cell_type": "markdown", - "id": "f625eaaa", - "metadata": {}, - "source": [ - "Man kann sich auch alle `keys` und `values` als spezielle Container geben lassen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21460e3a", - "metadata": {}, - "outputs": [], - "source": [ - "keys(EW)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a87d9788", - "metadata": {}, - "outputs": [], - "source": [ - "values(EW)" - ] - }, - { - "cell_type": "markdown", - "id": "97b96369", - "metadata": {}, - "source": [ - "Man kann über die `keys` iterieren...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "41e9189f", - "metadata": {}, - "outputs": [], - "source": [ - "for i in keys(EW)\n", - " n = EW[i]\n", - " println(\"Die Stadt $i hat $n Millionen Einwohner.\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "b2fe653a", - "metadata": {}, - "source": [ - "odere gleich über `key-value`-Paare.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0b445207", - "metadata": {}, - "outputs": [], - "source": [ - "for (stadt, ew) ∈ EW\n", - " println(\"$stadt : $ew Mill.\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "6fcd4019", - "metadata": {}, - "source": [ - "### Erweitern und Modifizieren\n", - "\n", - "Man kann in ein `Dict` zusätzliche `key-value`-Paare eintragen...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "94c4f076", - "metadata": {}, - "outputs": [], - "source": [ - "EW[\"Leipzig\"] = 0.52\n", - "EW[\"Dresden\"] = 0.52 \n", - "EW" - ] - }, - { - "cell_type": "markdown", - "id": "ed90d684", - "metadata": {}, - "source": [ - "und einen `value` ändern.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c57e8dd2", - "metadata": {}, - "outputs": [], - "source": [ - "# Oh, das war bei Leipzig die Zahl von 2010, nicht 2020\n", - "\n", - "EW[\"Leipzig\"] = 0.597\n", - "EW" - ] - }, - { - "cell_type": "markdown", - "id": "3d0eadd7", - "metadata": {}, - "source": [ - "Ein Paar kann über seinen `key` auch gelöscht werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0dfd9f2d", - "metadata": {}, - "outputs": [], - "source": [ - "delete!(EW, \"Dresden\")" - ] - }, - { - "cell_type": "markdown", - "id": "3db2aa1f", - "metadata": {}, - "source": [ - "Zahlreiche Funktionen können mit `Dicts` wie mit anderen Containern arbeiten.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1204aaab", - "metadata": {}, - "outputs": [], - "source": [ - "maximum(values(EW))" - ] - }, - { - "cell_type": "markdown", - "id": "6a4946b4", - "metadata": {}, - "source": [ - "### Anlegen eines leeren Dictionaries\n", - "\n", - "Ohne Typspezifikation ...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1f82ac79", - "metadata": {}, - "outputs": [], - "source": [ - "d1 = Dict()" - ] - }, - { - "cell_type": "markdown", - "id": "27c98eaf", - "metadata": {}, - "source": [ - "und mit Typspezifikation:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1b8f201e", - "metadata": {}, - "outputs": [], - "source": [ - "d2 = Dict{String, Int}()" - ] - }, - { - "cell_type": "markdown", - "id": "7fe71a3b", - "metadata": {}, - "source": [ - "### Umwandlung in Vektoren: `collect()`\n", - "\n", - "- `keys(dict)` und `values(dict)` sind spezielle Datentypen. \n", - "- Die Funktion `collect()` macht daraus eine Liste vom Typ `Vector`. \n", - "- `collect(dict)` liefert eine Liste vom Typ `Vector{Pair{S,T}}` \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2dc85bdd", - "metadata": {}, - "outputs": [], - "source": [ - "collect(EW)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "100dbbf1", - "metadata": {}, - "outputs": [], - "source": [ - "collect(keys(EW)), collect(values(EW))" - ] - }, - { - "cell_type": "markdown", - "id": "f9703f73", - "metadata": {}, - "source": [ - "### Geordnetes Iterieren über ein Dictionary\n", - "\n", - "Wir sortieren die Keys. Als Strings werden sie alphabetisch sortiert. Mit dem `rev`-Parameter wird rückwärts sortiert.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3c02f0ca", - "metadata": {}, - "outputs": [], - "source": [ - "for k in sort(collect(keys(EW)), rev = true)\n", - " n = EW[k]\n", - " println(\"$k hat $n Millionen Einw. \")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "c20f0654", - "metadata": {}, - "source": [ - "Wir sortieren `collect(dict)`. Das ist ein Vektor von Paaren. Mit `by` definieren wir, wonach zu sortieren ist: nach dem 2. Element des Paares. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "89ee04e9", - "metadata": {}, - "outputs": [], - "source": [ - "for (k,v) in sort(collect(EW), by = pair -> last(pair), rev=false)\n", - " println(\"$k hat $v Mill. EW\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "94ba9752", - "metadata": {}, - "source": [ - "### Eine Anwendung von Dictionaries: Zählen von Häufigkeiten\n", - "\n", - "Wir machen 'experimentelle Stochastik' mit 2 Würfeln: \n", - "\n", - "Gegeben sei `l`, eine Liste mit den Ergebnissen von 100 000 Pasch-Würfen, also 100 000 Zahlen zwischen 2 und 12.\n", - "\n", - "Wie häufig sind die Zahlen 2 bis 12?\n", - "\n", - "\n", - "Wir (lassen) würfeln:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a7ff829d", - "metadata": {}, - "outputs": [], - "source": [ - "l = rand(1:6, 100_000) .+ rand(1:6, 100_000)" - ] - }, - { - "cell_type": "markdown", - "id": "48a58503", - "metadata": {}, - "source": [ - "Wir zählen mit Hilfe eines Dictionaries die Häufigkeiten der Ereignisse. Dazu nehmen wir das Ereignis als `key` und seine Häufigkeit als `value`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dd2bcd79", - "metadata": {}, - "outputs": [], - "source": [ - "# In diesem Fall könnte man das auch mit einem einfachen Vektor\n", - "# lösen. Eine bessere Illustration wäre z.B. Worthäufigkeit in\n", - "# einem Text. Dann ist i keine ganze Zahl sondern ein Wort=String\n", - "\n", - "d = Dict{Int,Int}() # das Dict zum 'reinzählen'\n", - "\n", - "for i in l # für jedes i wird d[i] erhöht. \n", - " d[i] = get(d, i, 0) + 1 \n", - "end\n", - "d" - ] - }, - { - "cell_type": "markdown", - "id": "62fe53b9", - "metadata": {}, - "source": [ - "Das Ergebnis:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "154252d3", - "metadata": {}, - "outputs": [], - "source": [ - "using Plots\n", - "\n", - "plot(collect(keys(d)), collect(values(d)), seriestype=:scatter)" - ] - }, - { - "cell_type": "markdown", - "id": "dd482553", - "metadata": {}, - "source": [ - "##### Das Erklär-Bild dazu:\n", - "\n", - "[https://math.stackexchange.com/questions/1204396/why-is-the-sum-of-the-rolls-of-two-dices-a-binomial-distribution-what-is-define](https://math.stackexchange.com/questions/1204396/why-is-the-sum-of-the-rolls-of-two-dices-a-binomial-distribution-what-is-define)\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/7_ArraysP2.ipynb b/nb/7_ArraysP2.ipynb deleted file mode 100644 index 71e376c..0000000 --- a/nb/7_ArraysP2.ipynb +++ /dev/null @@ -1,2054 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e43a03dc", - "metadata": {}, - "source": [ - "# Vektoren, Matrizen, Arrays\n", - "\n", - "## Allgemeines \n", - "\n", - "Kommen wir nun zu den wohl wichtigsten Containern für numerische Mathematik: \n", - "\n", - "- Vektoren `Vector{T}` \n", - "- Matrizen `Matrix{T}` mit zwei Indizes \n", - "- N-dimensionale Arrays mit N Indizes `Array{T,N}`\n", - "\n", - "Tatsächlich ist `Vector{T}` ein Alias für `Array{T,1}` und `Matrix{T}` ein Alias für `Array{T,2}`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4b125a0a", - "metadata": {}, - "outputs": [], - "source": [ - "Vector{Float64} === Array{Float64,1} && Matrix{Float64} === Array{Float64,2}" - ] - }, - { - "cell_type": "markdown", - "id": "78eba0dc", - "metadata": {}, - "source": [ - "Beim Anlegen durch eine explizite Elementliste wird der 'kleinste gemeinsame Typ' für den Typparameter `T` ermittelt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6205881e", - "metadata": {}, - "outputs": [], - "source": [ - "v = [33, \"33\", 1.2]" - ] - }, - { - "cell_type": "markdown", - "id": "f720c669", - "metadata": {}, - "source": [ - "Falls `T` ein numerischer Typ ist, werden die Elemente in diesen Typ umgewandelt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b0e9d4a3", - "metadata": {}, - "outputs": [], - "source": [ - "v = [3//7, 4, 2im]" - ] - }, - { - "cell_type": "markdown", - "id": "d0cbc3d0", - "metadata": {}, - "source": [ - "Informationen über einen Array liefern die Funktionen:\n", - "\n", - "- `length(A)` --- Anzahl der Elemente\n", - "- `eltype(A)` --- Typ der Elemente\n", - "- `ndims(A)` --- Anzahl der Dimensionen (Indizes)\n", - "- `size(A)` --- Tupel mit den Dimensionen des Arrays \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "333529d4", - "metadata": {}, - "outputs": [], - "source": [ - "v1 = [12, 13, 15]\n", - "\n", - "m1 = [ 1 2.5\n", - " 6 -3 ]\n", - "\n", - "for f ∈ (length, eltype, ndims, size)\n", - " println(\"$(f)(v) = $(f(v)), $(f)(m1) = $(f(m1))\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "b21923e2", - "metadata": {}, - "source": [ - "- Die Stärke des 'klassischen' Arrays für das wissenschaftliche Rechnen besteht darin, dass es einfach nur ein zusammenhängendes Speichersegment ist, in dem die Komponenten gleicher Länge (z.B. 64 Bit) geordnet hintereinander abgespeichert sind. Damit ist der Speicherbedarf minimal und die Zugriffsgeschwindigkeit auf eine Komponente, sowohl beim Lesen als auch beim Modifizieren, maximal. Der Platz der Komponente `v[i]` ist sofort aus `i` berechenbar. \n", - "- Julias `Array{T,N}` (und damit Vektoren und Matrizen) ist für die üblichen numerischen Typen `T` in dieser Weise implementiert. Die Elemente werden *unboxed* gespeichert. Im Gegensatz dazu ist z.B. ein `Vector{Any}` implementiert als Liste von Adressen von Objekten *(boxed)* und nicht als Liste der Objekte selbst. \n", - "- Julias `Array{T,N}` speichert seine Elemente direkt *(unboxed)*, wenn `isbitstype(T) == true`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "50682513", - "metadata": {}, - "outputs": [], - "source": [ - "isbitstype(Float64), \n", - "isbitstype(Complex{Rational{Int64}}), \n", - "isbitstype(String)" - ] - }, - { - "cell_type": "markdown", - "id": "fc6ba262", - "metadata": {}, - "source": [ - "## Vektoren\n", - "\n", - "### Listen-artige Funktionen \n", - "\n", - "- `push!(vector, items...)` --- fügt Elemente am Ende des Vektors an\n", - "- `pushfirst!(vector, items...)` --- fügt Elemente am Anfang des Vektors an\n", - "- `pop!(vector)` --- entfernt letztes Element und liefert es als Ergebnis zurück,\n", - "- `popfirst!(vector)` --- entfernt erstes Element und liefert es zurück \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6a668c97", - "metadata": {}, - "outputs": [], - "source": [ - "v = Float64[] # leerer Vector{Float64}\n", - "\n", - "push!(v, 3, 7)\n", - "pushfirst!(v, 1)\n", - "\n", - "a = pop!(v)\n", - "println(\"a= $a\")\n", - "\n", - "push!(v, 17)" - ] - }, - { - "cell_type": "markdown", - "id": "15639f3a", - "metadata": {}, - "source": [ - "Ein `push!()` kann sehr aufwändig sein, da eventuell neuer Speicher alloziert und dann der ganze bestehende Vektor umkopiert werden muss. Julia optimiert das Speichermanagement. Es wird in einem solchen Fall Speicher auf Vorrat alloziert, so dass weitere `push!`s sehr schnell sind und man 'fast O(1)-Geschwindigkeit' erreicht. \n", - "\n", - "Trotzdem sollte man bei zeitkritischem Code und sehr großen Feldern Operationen wie `push!()` oder `resize()` vermeiden.\n", - "\n", - "### Weitere Konstruktoren\n", - "\n", - "Man kann Vektoren mit vorgegebener Länge und Typ uninitialisiert anlegen. Das geht am Schnellsten, die Elemente sind zufällige Bitmuster.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "50f6c3b9", - "metadata": {}, - "outputs": [], - "source": [ - "# fixe Länge 1000, uninitialisiert\n", - "\n", - "v = Vector{Float64}(undef, 1000)\n", - "v[345]" - ] - }, - { - "cell_type": "markdown", - "id": "5076f499", - "metadata": {}, - "source": [ - "- `zeros(n)` legt einen `Vector{Float64}` der Länge `n` an und initialisiert mit Null. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8207df1d", - "metadata": {}, - "outputs": [], - "source": [ - "v = zeros(7) " - ] - }, - { - "cell_type": "markdown", - "id": "7696ccaa", - "metadata": {}, - "source": [ - "- `zeros(T,n)` legt einen Nullvektor vom Typ `T` an.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6e578ab8", - "metadata": {}, - "outputs": [], - "source": [ - "v=zeros(Int, 4)" - ] - }, - { - "cell_type": "markdown", - "id": "6c9dc7a8", - "metadata": {}, - "source": [ - "- `fill(x, n)` legt `Vector{typeof(x)}` der Länge `n` an und füllt mit `x`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d9cba335", - "metadata": {}, - "outputs": [], - "source": [ - "v = fill(sqrt(2), 5)" - ] - }, - { - "cell_type": "markdown", - "id": "2868cf5c", - "metadata": {}, - "source": [ - "- `similar(v)` legt einen uninitialisierten Vektor von gleichem Typ und Größe wie `v` an.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "62eca8f9", - "metadata": {}, - "outputs": [], - "source": [ - "w = similar(v)" - ] - }, - { - "cell_type": "markdown", - "id": "7cbf3df1", - "metadata": {}, - "source": [ - "### Konstruktion durch implizite Schleife _(list comprehension)_\n", - "\n", - "Implizite `for`-Schleifen sind eine weitere Methode, Vektoren zu erzeugen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e07eaf25", - "metadata": {}, - "outputs": [], - "source": [ - "v4 = [i for i in 1.0:8]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2fce397a", - "metadata": {}, - "outputs": [], - "source": [ - "v5 = [log(i^2) for i in 1:4 ]" - ] - }, - { - "cell_type": "markdown", - "id": "d3432e22", - "metadata": {}, - "source": [ - "Man kann sogar noch ein `if` unterbringen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c61e9e2c", - "metadata": {}, - "outputs": [], - "source": [ - "v6 = [i^2 for i in 1:8 if i%3 != 2]" - ] - }, - { - "cell_type": "markdown", - "id": "7606acd1", - "metadata": {}, - "source": [ - "### Bitvektoren {#sec-bitvec}\n", - "\n", - "Neben `Vector{Bool}` gibt es noch den speziellen Datentyp `BitVector` (und allgemeiner auch `BitArray`) zur Speicherung von Feldern mit Wahrheitswerten. \n", - "\n", - "Während für die Speicherung eines `Bool`s ein Byte verwendet wird, erfolgt die Speicherung in einem BitVector bitweise. \n", - "\n", - "Der Konstruktor wandelt einen \n", - "`Vector{Bool}` in einen `BitVector` um.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0d5b1e39", - "metadata": {}, - "outputs": [], - "source": [ - "vb = BitVector([true, false, true, true])" - ] - }, - { - "cell_type": "markdown", - "id": "426cefd2", - "metadata": {}, - "source": [ - "Für die Gegenrichtung gibt es `collect()`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "65291775", - "metadata": {}, - "outputs": [], - "source": [ - "collect(vb)" - ] - }, - { - "cell_type": "markdown", - "id": "3f56c7c8", - "metadata": {}, - "source": [ - "BitVectoren entstehen z.B. als Ergebnis von elementweisen Vergleichen (s. @sec-broadcast).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2584c04e", - "metadata": {}, - "outputs": [], - "source": [ - "v4 .> 3.5" - ] - }, - { - "cell_type": "markdown", - "id": "6a0f2b5e", - "metadata": {}, - "source": [ - "### Indizierung\n", - "\n", - "Indizes sind Ordinalzahlen. Also __startet die Indexzählung mit 1.__\n", - "\n", - "Als Index kann man verwenden:\n", - "\n", - " - Integer\n", - " - Integer-wertigen Range (gleiche Länge oder kürzer)\n", - " - Integer-Vektor (gleiche Länge oder kürzer)\n", - " - Bool-Vektor oder BitVector (gleiche Länge)\n", - " \n", - " \n", - "Mit Indizes kann man Arrayelemente/teile lesen und schreiben.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9180ff62", - "metadata": {}, - "outputs": [], - "source": [ - "v = [ 3i + 5.2 for i in 1:8]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cb5a9547", - "metadata": {}, - "outputs": [], - "source": [ - "v[5]" - ] - }, - { - "cell_type": "markdown", - "id": "e58751f6", - "metadata": {}, - "source": [ - "Bei Zuweisungen wird die rechte Seite wenn nötig mit `convert(T,x)` in den Vektorelementetyp umgewandelt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d029af20", - "metadata": {}, - "outputs": [], - "source": [ - "v[6] = 9999\n", - "v" - ] - }, - { - "cell_type": "markdown", - "id": "2561448e", - "metadata": {}, - "source": [ - "Überschreiten der Indexgrenzen führt zu einem `BoundsError`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "06224d52", - "metadata": {}, - "outputs": [], - "source": [ - "v[77]" - ] - }, - { - "cell_type": "markdown", - "id": "deb2c6b3", - "metadata": {}, - "source": [ - "Mit einem `range`-Objekt kann man einen Teilvektor adressieren.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "322752f1", - "metadata": {}, - "outputs": [], - "source": [ - "vp = v[3:5]\n", - "vp" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a24080ff", - "metadata": {}, - "outputs": [], - "source": [ - "vp = v[1:2:7] # range mit Schrittweite\n", - "vp" - ] - }, - { - "cell_type": "markdown", - "id": "9a7afae9", - "metadata": {}, - "source": [ - "- Bei der Verwendung als Index kann in einem Range der Spezialwert `end` verwendet werden.\n", - "- Bei der Verwendung als Index kann der \"leere\" Range `:` als Abkürzung von `1:end` verwendet werden. Das ist nützlich bei Matrizen: `A[:, 3]` adressiert die gesamte 3. Spalte von `A`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e7bfe889", - "metadata": {}, - "outputs": [], - "source": [ - "v[6:end] = [7, 7, 7]\n", - "v" - ] - }, - { - "cell_type": "markdown", - "id": "178a0bd2", - "metadata": {}, - "source": [ - "#### Indirekte Indizierung\n", - "\n", - "Die indirekte Indizierung mit einem *Vector of Integers/Indices* erfolgt nach der Formel \n", - "\n", - "\n", - "$v[ [i_1,\\ i_2,\\ i_3,...]] = [\\ v[i_1],\\ v[i_2],\\ v[i_3],...]$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f72a76df", - "metadata": {}, - "outputs": [], - "source": [ - "v[ [1, 3, 4] ]" - ] - }, - { - "cell_type": "markdown", - "id": "f2d76c2c", - "metadata": {}, - "source": [ - "ist also gleich\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5c9556da", - "metadata": {}, - "outputs": [], - "source": [ - "[ v[1], v[3], v[4] ]" - ] - }, - { - "cell_type": "markdown", - "id": "3d7b83ee", - "metadata": {}, - "source": [ - "#### Indizierung mit einem Vektor von Wahrheitswerten\n", - "\n", - "Als Index kann man auch einen `Vector{Bool}` oder `BitVector` (s. @sec-bitvec) **derselben Länge** verwenden. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0995d191", - "metadata": {}, - "outputs": [], - "source": [ - "v[ [true, true, false, false, true, false, true, true] ]" - ] - }, - { - "cell_type": "markdown", - "id": "f7ef567d", - "metadata": {}, - "source": [ - "Das ist nützlich, da man z.B.\n", - "\n", - " - Tests broadcasten kann (s. @sec-broadcast),\n", - " - diese Tests dann einen BitVector liefern und\n", - " - bei Bedarf solche Bitvektoren durch die Bit-weisen Operatoren `&` und `|` verknüpft werden können. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "eda29b0d", - "metadata": {}, - "outputs": [], - "source": [ - "v[ (v .> 13) .& (v.<20) ]" - ] - }, - { - "cell_type": "markdown", - "id": "3f46137f", - "metadata": {}, - "source": [ - "## Matrizen und Arrays\n", - "\n", - "Die bisher vorgestellten Methoden für Vektoren übertragen sich auch auf höherdimensionale Arrays.\n", - "\n", - "Man kann sie uninitialisiert anlegen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a8bf798b", - "metadata": {}, - "outputs": [], - "source": [ - "A = Array{Float64,3}(undef, 6,9,3)" - ] - }, - { - "cell_type": "markdown", - "id": "60e20aae", - "metadata": {}, - "source": [ - "In den meisten Funktionen kann man die Dimensionen auch als Tupel übergeben. Die obige Anweisung lässt sich auch so schreiben:\n", - "\n", - "```julia\n", - "A = Array{Float64, 3}(undef, (6,9,3)) \n", - "```\n", - "\n", - "Funktionen wie `zeros()` usw. funktionieren natürlich auch.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "50627ef8", - "metadata": {}, - "outputs": [], - "source": [ - "m2 = zeros(3, 4, 2) # oder zeros((3,4,2)) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fa2da287", - "metadata": {}, - "outputs": [], - "source": [ - "M = fill(5 , (3, 3)) # oder fill(5, 3, 3)" - ] - }, - { - "cell_type": "markdown", - "id": "79c237c5", - "metadata": {}, - "source": [ - "Die Funktion `similar()`, die einen Array gleicher Größe uninitialisiert erzeugt, kann auch einen Typ als weiteres Argument bekommen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "967c0a3e", - "metadata": {}, - "outputs": [], - "source": [ - "M2 = similar(M, Float64)" - ] - }, - { - "cell_type": "markdown", - "id": "381254e3", - "metadata": {}, - "source": [ - "### Konstruktion durch explizite Elementliste\n", - "\n", - "Während man Vektoren kommagetrennt in eckigen Klammern notiert, ist die Notation für höherdimensionale Objekte etwas anders. \n", - "\n", - "- Eine Matrix:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7100bcaf", - "metadata": {}, - "outputs": [], - "source": [ - "M2 = [2 3 -1\n", - " 4 5 -2]" - ] - }, - { - "cell_type": "markdown", - "id": "45bef96a", - "metadata": {}, - "source": [ - "- dieselbe Matrix:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7e6caf84", - "metadata": {}, - "outputs": [], - "source": [ - "M2 = [2 3 -1; 4 5 -2]" - ] - }, - { - "cell_type": "markdown", - "id": "be6fedc8", - "metadata": {}, - "source": [ - "- Ein Array mit 3 Indizes:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3f2233ce", - "metadata": {}, - "outputs": [], - "source": [ - "M3 = [2 3 -1 \n", - " 4 5 6 ;;;\n", - " 7 8 9\n", - " 11 12 13]" - ] - }, - { - "cell_type": "markdown", - "id": "e3bee379", - "metadata": {}, - "source": [ - "- und nochmal die Matrix `M2`:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "efa9ecd7", - "metadata": {}, - "outputs": [], - "source": [ - "M2 = [2;4;; 3;5;; -1;-2]" - ] - }, - { - "cell_type": "markdown", - "id": "fa6e923a", - "metadata": {}, - "source": [ - "Im letzten Beispiel kommen diese Regeln zur Anwendung:\n", - "\n", - "- Trenner ist das Semikolon.\n", - "- Ein Semikolon `;` erhöht den 1. Index.\n", - "- Zwei Semikolons `;;` erhöhen den 2. Index.\n", - "- Drei Semikolons `;;;` erhöhen den 3. Index usw. \n", - "\n", - "In den Beispielen davor wurde folgende Syntaktische Verschönerung (_syntactic sugar_) angewendet:\n", - "\n", - "- Leerzeichen trennen wie 2 Semikolons -- erhöht also den 2. Index: $\\quad a_{12}\\quad a_{13}\\quad a_{14}\\ ...$\n", - "- Zeilenumbruch trennt wie ein Semikolon -- erhöht also den 1. Index.\n", - "\n", - "\n", - ":::{.callout-important}\n", - "\n", - "- Vektorschreibweise mit Komma als Trenner geht nur bei Vektoren, nicht mit \"Semikolon, Leerzeichen, Newline\" mischen! \n", - "- Vektoren, $1\\!\\times\\!n$-Matrizen und $n\\!\\times\\!1$-Matrizen sind drei verschiedene Dinge!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "20499e99", - "metadata": {}, - "outputs": [], - "source": [ - "v1 = [2,3,4]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e8554e3f", - "metadata": {}, - "outputs": [], - "source": [ - "v2 = [2;3;4]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d42f242f", - "metadata": {}, - "outputs": [], - "source": [ - "v3 = [2 3 4]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f76b20d5", - "metadata": {}, - "outputs": [], - "source": [ - "v3 = [2;3;4;;]" - ] - }, - { - "cell_type": "markdown", - "id": "a049e8a8", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "\n", - "Einen \"vector of vectors\" a la C/C++ kann man natürlich auch konstruieren. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "73cfb832", - "metadata": {}, - "outputs": [], - "source": [ - "v = [[2,3,4], [5,6,7,8]]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "55f2f419", - "metadata": {}, - "outputs": [], - "source": [ - "v[2][3]" - ] - }, - { - "cell_type": "markdown", - "id": "69072c6f", - "metadata": {}, - "source": [ - "Das sollte man nur in Spezialfällen tun. Die Array-Sprache von Julia ist in der Regel bequemer und schneller.\n", - "\n", - "### Indizes, Teilfelder, Slices\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f8d1140f", - "metadata": {}, - "outputs": [], - "source": [ - "# 6x6 Matrix mit Zufallszahlen gleichverteilt aus [0,1) ∈ Float64\n", - "A = rand(6,6)" - ] - }, - { - "cell_type": "markdown", - "id": "7ca06ccd", - "metadata": {}, - "source": [ - "Die übliche Indexnotation:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "117b78c9", - "metadata": {}, - "outputs": [], - "source": [ - "A[2, 3] = 77.77777\n", - "A" - ] - }, - { - "cell_type": "markdown", - "id": "6a1d738b", - "metadata": {}, - "source": [ - "Man kann mit Ranges Teilfelder adressieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "733f15a6", - "metadata": {}, - "outputs": [], - "source": [ - "B = A[1:2, 1:3]" - ] - }, - { - "cell_type": "markdown", - "id": "212c6e6d", - "metadata": {}, - "source": [ - "Das Adressieren von Teilen mit geringerer Dimension wird auch *slicing* genannt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2190a0d6", - "metadata": {}, - "outputs": [], - "source": [ - "# die 3. Spalte als Vektor (slicing)\n", - "\n", - "C = A[:, 3]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "94e3dc5b", - "metadata": {}, - "outputs": [], - "source": [ - "# die 3. Zeile als Vektor (slicing)\n", - "\n", - "E = A[3, :]" - ] - }, - { - "cell_type": "markdown", - "id": "45c89587", - "metadata": {}, - "source": [ - "Natürlich sind damit auch Zuweisungen möglich:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "beca175d", - "metadata": {}, - "outputs": [], - "source": [ - "# Man kann slices und Teilfeldern auch etwas zuweisen \n", - "\n", - "A[2, :] = [1,2,3,4,5,6]\n", - "A" - ] - }, - { - "cell_type": "markdown", - "id": "9dd8da68", - "metadata": {}, - "source": [ - "## Verhalten bei Zuweisungen, `copy()` und `deepcopy()`, Views\n", - "\n", - "### Zuweisungen und Kopien\n", - "\n", - "- Variablen sind Referenzen auf Objekte. \n", - "- _Eine Zuweisung zu einer Variablen erzeugt kein neues Objekt._\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e7ece88d", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1, 2, 3]\n", - "B = A" - ] - }, - { - "cell_type": "markdown", - "id": "390e8338", - "metadata": {}, - "source": [ - "`A` und `B` sind jetzt Namen desselben Objekts.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ad71682b", - "metadata": {}, - "outputs": [], - "source": [ - "A[1] = 77\n", - "@show B;" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9422450b", - "metadata": {}, - "outputs": [], - "source": [ - "B[3] = 300\n", - "@show A;" - ] - }, - { - "cell_type": "markdown", - "id": "ce960e49", - "metadata": {}, - "source": [ - "Dieses Verhalten spart viel Zeit und Speicher, ist aber nicht immer gewünscht. \n", - "Die Funktion `copy()` erzeugt eine 'echte' Kopie des Objekts.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "61fd903e", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1, 2, 3]\n", - "B = copy(A)\n", - "A[1] = 100\n", - "@show A B;" - ] - }, - { - "cell_type": "markdown", - "id": "cf24b145", - "metadata": {}, - "source": [ - "Die Funktion \n", - "`deepcopy(A)` kopiert rekursiv. Auch von den Elementen, aus denen `A` besteht, werden (wieder rekursive) Kopien erstellt. \n", - "\n", - "Solange ein Array nur primitive Objekte (Zahlen) enthält, sind `copy()` und `deepcopy()` äquivalent. \n", - "\n", - "Das folgende Beispiel zeigt den Unterschied zwischen `copy()` und `deepcopy()`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "174a9513", - "metadata": {}, - "outputs": [], - "source": [ - "mutable struct Person\n", - " name :: String\n", - " age :: Int\n", - "end\n", - "\n", - "A = [Person(\"Meier\", 20), Person(\"Müller\", 21), Person(\"Schmidt\", 23)]\n", - "B = A\n", - "C = copy(A)\n", - "D = deepcopy(A)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "79dac2ba", - "metadata": {}, - "outputs": [], - "source": [ - "A[1] = Person(\"Mustermann\", 83)\n", - "A[3].age = 199 \n", - "\n", - "@show B C D;" - ] - }, - { - "cell_type": "markdown", - "id": "8adee725", - "metadata": {}, - "source": [ - "### Views\n", - "\n", - "Wenn man mittels *indices/ranges/slices* einer Variablen ein Teilstück eines Arrays zuweist, \n", - "wird von Julia grundsätzlich **ein neues Objekt** konstruiert.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0aeffcf9", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1 2 3\n", - " 3 4 5]\n", - "\n", - "v = A[:, 2]\n", - "@show v\n", - "\n", - "A[1, 2] = 77\n", - "@show A v;" - ] - }, - { - "cell_type": "markdown", - "id": "1e2f7d51", - "metadata": {}, - "source": [ - "Manchmal möchte man aber gerade hier eine Referenz-Semantik haben im Sinne von: \"Vektor `v` soll der 2. Spaltenvektor von `A` sein und auch bleiben (d.h., sich mitändern, wenn sich `A` ändert).\"\n", - "\n", - "Dies bezeichnet man in Julia als *views*: Wir wollen, dass die Variable `v` nur einen 'alternativen Blick' auf die Matrix `A` darstellt.\n", - "\n", - "Das kann man erreichen durch das `@view`-Macro: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1ea24972", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1 2 3\n", - " 3 4 5]\n", - "\n", - "v = @view A[:,2]\n", - "@show v\n", - "\n", - "A[1, 2] = 77\n", - "@show v;" - ] - }, - { - "cell_type": "markdown", - "id": "929d0c0c", - "metadata": {}, - "source": [ - "Diese Technik wird von Julia aus Effizienzgründen auch bei einigen Funktionen der linearen Algebra verwendet. \n", - "Ein Beispiel ist der Operator `'`, der zu einer Matrix `A` die adjungierte Matrix `A'` liefert.\n", - "\n", - "- Die adjungierte _(adjoint)_ Matrix `A'` ist die transponierte und elementweise komplex-konjugierte Matrix zu `A`. \n", - "- Der Parser macht daraus den Funktionsaufruf `adjoint(A)`. \n", - "- Für reelle Matrizen ist die Adjungierte gleich der transponierten Matrix.\n", - "- Julia implementiert `adjoint()` als _lazy function_, d.h., \n", - "- es wird aus Effizienzgründen kein neues Objekt konstruiert, sondern nur ein alternativer 'View' auf die Matrix (\"mit vertauschten Indizes\") und ein alternativer 'View' auf die Einträge (mit Vorzeichenwechsel im Imaginärteil).\n", - "- Aus Vektoren macht `adjoint()` eine $1\\!\\times\\!n$-Matrix (einen Zeilenvektor).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4eab95b5", - "metadata": {}, - "outputs": [], - "source": [ - "A = [ 1. 2.\n", - " 3. 4.]\n", - "B = A'" - ] - }, - { - "cell_type": "markdown", - "id": "05788cae", - "metadata": {}, - "source": [ - "Die Matrix `B` ist nur ein modifizierter 'View' auf `A`:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8cbbd3b6", - "metadata": {}, - "outputs": [], - "source": [ - "A[1, 2] =10\n", - "B" - ] - }, - { - "cell_type": "markdown", - "id": "67cfc86f", - "metadata": {}, - "source": [ - "Aus Vektoren macht `adjoint()` eine $1\\!\\times\\!n$-Matrix (einen Zeilenvektor).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5bbd675d", - "metadata": {}, - "outputs": [], - "source": [ - "v = [1, 2, 3]\n", - "v'" - ] - }, - { - "cell_type": "markdown", - "id": "c6a6095a", - "metadata": {}, - "source": [ - "Eine weitere solche Funktion, die einen alternativen 'View', eine andere Indizierung, derselben Daten \n", - "liefert, ist `reshape()`. \n", - "\n", - "Hier wird ein Vektor mit 12 Einträgen in eine 3x4-Matrix verwandelt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6f9b3031", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1,2,3,4,5,6,7,8,9,10,11,12]\n", - "\n", - "B = reshape(A, 3, 4) " - ] - }, - { - "cell_type": "markdown", - "id": "a113beb5", - "metadata": {}, - "source": [ - "## Speicherung eines Arrays\n", - "\n", - "- Speicher wird linear adressiert. Eine Matrix kann zeilenweise _(row major)_ oder spaltenweise _(column major)_ im Speicher angeordnet sein. \n", - "- C/C++/Python(NumPy) verwenden eine zeilenweise Speicherung: Die 4 Elemente einer 2x2-Matrix sind abgespeichert in der Reihenfolge $a_{11},a_{12},a_{21},a_{22}$. \n", - "- Julia, Fortran, Matlab speichern spaltenweise: $a_{11},a_{21},a_{12},a_{22}$. \n", - "\n", - "Diese Information ist wichtig, um effizient über Matrizen zu iterieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d465b690", - "metadata": {}, - "outputs": [], - "source": [ - "function column_major_add(A, B)\n", - " (n,m) = size(A)\n", - " for j = 1:m\n", - " for i = 1:n # innere Schleife durchläuft eine Spalte\n", - " A[i,j] += B[i,j]\n", - " end\n", - " end\n", - "end\n", - "\n", - "function row_major_add(A, B)\n", - " (n,m) = size(A)\n", - " for i = 1:n\n", - " for j = 1:m # inere Schleife durchläuft eine Zeile\n", - " A[i,j] += B[i,j]\n", - " end\n", - " end\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "eba4dc73", - "metadata": {}, - "outputs": [], - "source": [ - "A = rand(10000, 10000);\n", - "B = rand(10000, 10000);" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ae245931", - "metadata": {}, - "outputs": [], - "source": [ - "using BenchmarkTools\n", - "\n", - "@benchmark row_major_add($A, $B) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "604ed987", - "metadata": {}, - "outputs": [], - "source": [ - "@benchmark column_major_add($A, $B)" - ] - }, - { - "cell_type": "markdown", - "id": "18adb785", - "metadata": {}, - "source": [ - "### Lokalität von Speicherzugriffen und _Caching_\n", - "\n", - "Wir haben gesehen, dass die Reihenfolge von innerem und äußerem Loop einen erheblichen Geschwindigkeitsunterschied macht:\n", - "\n", - "__Es ist effizienter, wenn die innerste Schleife über den linken Index läuft__, also eine Spalte und nicht eine Zeile durchläuft. Die Ursache dafür liegt in der Architektur moderner Prozessoren.\n", - "\n", - "- Speicherzugriffe erfolgt über mehrere Cache-Ebenen. \n", - "- Ein _cache miss_, der ein Nachladen aus langsameren Caches auslöst, bremst aus.\n", - "- Es werden immer gleich größere Speicherblöcke nachgeladen, um die Häufigkeit von _cache misses_ zu minimieren.\n", - "- Daher ist es wichtig, Speicherzugriffe möglichst lokal zu organisieren.\n", - "\n", - "::: {.content-visible when-format=\"html\"}\n", - "![Speicherhierarchie von Intel-Prozessoren, aus: Victor Eijkhout,_Introduction to High-Performance Scientific Computing_, [https://theartofhpc.com/](https://theartofhpc.com/)](../images/cache.png){width=\"75%\"}\n", - "\n", - ":::\n", - "\n", - "::: {.content-visible when-format=\"pdf\"}\n", - "![Speicherhierarchie von Intel-Prozessoren, aus: Victor Eijkhout,_Introduction to High-Performance Scientific Computing_, [https://theartofhpc.com/](https://theartofhpc.com/)](../images/cache.png){width=\"70%\"}\n", - ":::\n", - "\n", - "\n", - "## Mathematische Operationen mit Arrays\n", - "\n", - "Arrays der gleichen Dimension (z.B. alle $7\\!\\times\\!3$-Matrizen) bilden einen linearen Raum. \n", - "\n", - " - Sie können mit Skalaren multipliziert werden und\n", - " - sie können addiert und subtrahiert werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dfb3003d", - "metadata": {}, - "outputs": [], - "source": [ - "0.5 * [2, 3, 4, 5]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "48d71570", - "metadata": {}, - "outputs": [], - "source": [ - "0.5 * [ 1 3\n", - " 2 7] - [ 2 3; 1 2]" - ] - }, - { - "cell_type": "markdown", - "id": "6c87a401", - "metadata": {}, - "source": [ - "### Matrixprodukt\n", - "\n", - "Das Matrixprodukt ist definiert für \n", - "\n", - ":::{.narrow}\n", - "\n", - "| 1. Faktor | 2. Faktor | Produkt |\n", - "| :-: | :-: | :-: |\n", - "| $(n\\!\\times\\!m)$-Matrix | $(m\\!\\times\\!k)$-Matrix | $(n\\times k)$-Matrix|\n", - "| $(n\\!\\times\\!m)$-Matrix | $m$-Vektor | $n$-Vektor |\n", - "| $(1\\!\\times\\!m)$-Zeilenvektor | $(m\\!\\times\\!n)$-Matrix | $n$-Vektor |\n", - "| $(1\\!\\times\\!m)$-Zeilenvektor | $m$-Vektor | Skalarprodukt |\n", - "| $m$-Vektor | $(1\\times n)$-Zeilenvektor | $(m\\!\\times\\!n)$-Matrix |\n", - "\n", - ":::\n", - "\n", - "Beispiele:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "05935615", - "metadata": {}, - "outputs": [], - "source": [ - "A = [1 2 3\n", - " 4 5 6]\n", - "v = [2, 3]\n", - "w = [1, 3, 4];" - ] - }, - { - "cell_type": "markdown", - "id": "dce2784e", - "metadata": {}, - "source": [ - "- (2,3)-Matrix `*` (3,2)-Matrix\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7598bc25", - "metadata": {}, - "outputs": [], - "source": [ - "A * A'" - ] - }, - { - "cell_type": "markdown", - "id": "55f9d6b9", - "metadata": {}, - "source": [ - "- (3,2)-Matrix `*` (2,3)-Matrix\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "564ad780", - "metadata": {}, - "outputs": [], - "source": [ - "A' * A" - ] - }, - { - "cell_type": "markdown", - "id": "40ac054a", - "metadata": {}, - "source": [ - "- (2,3)-Matrix `*` 3-Vektor\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b786671d", - "metadata": {}, - "outputs": [], - "source": [ - "A * w" - ] - }, - { - "cell_type": "markdown", - "id": "2e1d3ac5", - "metadata": {}, - "source": [ - "- (1,2)-Vektore `*` (2,3)-Matrix\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0ffa79ec", - "metadata": {}, - "outputs": [], - "source": [ - "v' * A" - ] - }, - { - "cell_type": "markdown", - "id": "63ef7bb9", - "metadata": {}, - "source": [ - "- (3,2)-Matrix `*` 2-Vektor\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b0f948d5", - "metadata": {}, - "outputs": [], - "source": [ - "A' * v" - ] - }, - { - "cell_type": "markdown", - "id": "fd1bc853", - "metadata": {}, - "source": [ - "- (1,2)-Vektor `*` 2-Vektor (Skalarprodukt)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5dab68d0", - "metadata": {}, - "outputs": [], - "source": [ - "v' * v" - ] - }, - { - "cell_type": "markdown", - "id": "f968aace", - "metadata": {}, - "source": [ - "2-Vektor `*` (1,3)-Vektor (äußeres Produkt) \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1e9d367d", - "metadata": {}, - "outputs": [], - "source": [ - "v * w'" - ] - }, - { - "cell_type": "markdown", - "id": "5550f800", - "metadata": {}, - "source": [ - "## Broadcasting {#sec-broadcast}\n", - "\n", - "- Beim _broadcasting_ werden Operationen oder Funktionen __elementweise__ auf Arrays angewendet.\n", - "- Die Syntax dafür ist ein Punkt _vor_ einem Operationszeichen oder _nach_ einem Funktionsnamen. \n", - "- Der Parser setzt `f.(x,y)` um zu `broadcast(f, x, y)` und analog für Operatoren `x .⊙ y` zu `broadcast(⊙, z, y)`. \n", - "- Dabei werden Operanden, denen eine oder mehrere Dimensionen fehlen, in diesen Dimensionen (virtuell) vervielfältigt. \n", - "- Das *broadcasting* von Zuweisungen `.=`, `.+=`,... verändert die Semantik. Es wird kein neues Objekt erzeugt, sondern die Werte werden in das links stehende Objekt (welches die richtige Dimension haben muss) eingetragen.\n", - "\n", - "\n", - "Einige Beispiele:\n", - "\n", - "- Elementweise Anwendung einer Funktion\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cf644168", - "metadata": {}, - "outputs": [], - "source": [ - "sin.([1, 2, 3])" - ] - }, - { - "cell_type": "markdown", - "id": "ad8b4971", - "metadata": {}, - "source": [ - "- Das Folgende liefert nicht die algebraische [Wurzel aus einer Matrix](https://de.wikipedia.org/wiki/Quadratwurzel_einer_Matrix), sondern die elementweise Wurzel aus jedem Eintrag. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b4538387", - "metadata": {}, - "outputs": [], - "source": [ - "A = [8 2\n", - " 3 4]\n", - "\n", - "sqrt.(A)" - ] - }, - { - "cell_type": "markdown", - "id": "3707abc5", - "metadata": {}, - "source": [ - "- Das Folgende liefert nicht $A^2$, sondern die Einträge werden quadriert.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5f37e6fb", - "metadata": {}, - "outputs": [], - "source": [ - "A.^2 " - ] - }, - { - "cell_type": "markdown", - "id": "e29962a4", - "metadata": {}, - "source": [ - "- Zum Vergleich das Ergebnis der algebraischen Operationen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1b596daf", - "metadata": {}, - "outputs": [], - "source": [ - "@show A^2 A^(1/2);" - ] - }, - { - "cell_type": "markdown", - "id": "8f03b0b1", - "metadata": {}, - "source": [ - "- Broadcasting geht auch mit Funktionen mehrerer Variablen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e6b8bee2", - "metadata": {}, - "outputs": [], - "source": [ - "hyp(a,b) = sqrt(a^2+b^2)\n", - "\n", - "B = [3 4\n", - " 5 7]\n", - "\n", - "hyp.(A, B) " - ] - }, - { - "cell_type": "markdown", - "id": "1b26105a", - "metadata": {}, - "source": [ - "Bei Operanden verschiedener Dimension wird der Operand mit fehlenden Dimensionen in diesen durch Vervielfältigung virtuell \n", - "'aufgeblasen'.\n", - "\n", - "Wir addieren einen Skalar zu einer Matrix:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e93a5c94", - "metadata": {}, - "outputs": [], - "source": [ - "A = [ 1 2 3\n", - " 4 5 6]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1ffed9b6", - "metadata": {}, - "outputs": [], - "source": [ - "A .+ 300" - ] - }, - { - "cell_type": "markdown", - "id": "20ad8893", - "metadata": {}, - "source": [ - "Der Skalar wurde durch Replikation auf dieselbe Dimension wie die Matrix gebracht. Wir lassen uns von `broadcast()` die Form des 2. Operanden nach dem *broadcasting* anzeigen: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f1cb0ee6", - "metadata": {}, - "outputs": [], - "source": [ - "broadcast( (x,y) -> y, A, 300)" - ] - }, - { - "cell_type": "markdown", - "id": "241dbfa0", - "metadata": {}, - "source": [ - "(Natürlich findet diese Replikation nur virtuell statt. Dieses Objekt wird bei anderen Operationen nicht wirklich erzeugt.)\n", - "\n", - "Als weiteres Beispiel: Matrix und (Spalten-)Vektor\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "429dabe1", - "metadata": {}, - "outputs": [], - "source": [ - "A .+ [10, 20]" - ] - }, - { - "cell_type": "markdown", - "id": "de953456", - "metadata": {}, - "source": [ - "Der Vektor wird durch Wiederholung der Spalten aufgeblasen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9f5535f6", - "metadata": {}, - "outputs": [], - "source": [ - "broadcast((x,y)->y, A, [10,20])" - ] - }, - { - "cell_type": "markdown", - "id": "2627365f", - "metadata": {}, - "source": [ - "Matrix und Zeilenvektor: Der Zeilenvektor wird zeilenweise vervielfältigt:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "962474ab", - "metadata": {}, - "outputs": [], - "source": [ - "A .* [1,2,3]' # Adjungierter Vektor" - ] - }, - { - "cell_type": "markdown", - "id": "ac7a3201", - "metadata": {}, - "source": [ - "Der 2. Operand wird von `broadcast()` durch Vervielfältigung der Zeilen 'aufgeblasen'.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d83acb56", - "metadata": {}, - "outputs": [], - "source": [ - "broadcast((x,y)->y, A, [1,2,3]')" - ] - }, - { - "cell_type": "markdown", - "id": "80457191", - "metadata": {}, - "source": [ - "#### _Broadcasting_ bei Zuweisungen\n", - "\n", - "Zuweisungen `=`, `+=`, `/=`,..., bei denen links ein Name steht, laufen in Julia so ab, dass aus der rechten Seite ein Objekt konstruiert und diesem Objekt der neue Name zugewiesen wird. \n", - "\n", - "Beim Arbeiten mit Arrays will man allerdings sehr oft aus Effizienzgründen einen bestehenden Array weiterverwenden. Die rechts berechneten Einträge sollen in das bereits existierende Objekt auf der linken Seite eingetragen werden. \n", - "\n", - "Das erreicht man mit den Broadcast-Varianten `.=`, `.+=`,... der Zuweisungsoperatoren.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bee75c40", - "metadata": {}, - "outputs": [], - "source": [ - "A .= 3" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bf5e8b92", - "metadata": {}, - "outputs": [], - "source": [ - "A .+= [1, 4]" - ] - }, - { - "cell_type": "markdown", - "id": "98dd945c", - "metadata": {}, - "source": [ - "## Weitere Array-Funktionen - eine Auswahl\n", - "\n", - "Julia stellt eine große Anzahl von Funktionen bereit, die mit Arrays arbeiten.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "519a4401", - "metadata": {}, - "outputs": [], - "source": [ - "A = [22 -17 8 ; 4 6 9]" - ] - }, - { - "cell_type": "markdown", - "id": "439eed6b", - "metadata": {}, - "source": [ - "- Finde das Maximum\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ec143467", - "metadata": {}, - "outputs": [], - "source": [ - "maximum(A)" - ] - }, - { - "cell_type": "markdown", - "id": "d15dfe99", - "metadata": {}, - "source": [ - "- Finde das Maximum jeder Spalte\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "533c06d7", - "metadata": {}, - "outputs": [], - "source": [ - "maximum(A, dims=1) " - ] - }, - { - "cell_type": "markdown", - "id": "5f1a1b2a", - "metadata": {}, - "source": [ - "- Finde das Maximum jeder Zeile\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c34651ef", - "metadata": {}, - "outputs": [], - "source": [ - "maximum(A, dims=2)" - ] - }, - { - "cell_type": "markdown", - "id": "f3fdef0e", - "metadata": {}, - "source": [ - "- Finde das Minimum und seine Position\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "98e5091d", - "metadata": {}, - "outputs": [], - "source": [ - "amin, i = findmin(A)" - ] - }, - { - "cell_type": "markdown", - "id": "2e7763ec", - "metadata": {}, - "source": [ - "- Was ist ein `CartesianIndex`?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af1ba0fd", - "metadata": {}, - "outputs": [], - "source": [ - "dump(i)" - ] - }, - { - "cell_type": "markdown", - "id": "6ab6f7d3", - "metadata": {}, - "source": [ - "- Extrahiere die Indizes des Minimum als Tupel\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d05a38b9", - "metadata": {}, - "outputs": [], - "source": [ - "i.I" - ] - }, - { - "cell_type": "markdown", - "id": "086a84fa", - "metadata": {}, - "source": [ - "- Summe und Produkt aller Einträge\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "da8c7d9d", - "metadata": {}, - "outputs": [], - "source": [ - "sum(A), prod(A)" - ] - }, - { - "cell_type": "markdown", - "id": "00dafdb6", - "metadata": {}, - "source": [ - "- Spaltensumme (1. Index wird reduziert)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5396cf9f", - "metadata": {}, - "outputs": [], - "source": [ - "sum(A, dims=1) " - ] - }, - { - "cell_type": "markdown", - "id": "22bb7bc0", - "metadata": {}, - "source": [ - "- Zeilensummen (2. Index wird reduziert)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d4b2df7a", - "metadata": {}, - "outputs": [], - "source": [ - "sum(A, dims=2) " - ] - }, - { - "cell_type": "markdown", - "id": "8034a3be", - "metadata": {}, - "source": [ - "- Summiere nach elementweiser Anwendung einer Funktion\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7ba1e90d", - "metadata": {}, - "outputs": [], - "source": [ - "sum(x->sqrt(abs(x)), A) # sum_ij sqrt(|a_ij|)" - ] - }, - { - "cell_type": "markdown", - "id": "3e5683c0", - "metadata": {}, - "source": [ - "- Reduziere (falte) den Array mit einer Funktion\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "159aaf26", - "metadata": {}, - "outputs": [], - "source": [ - "reduce(+, A) # equivalent to sum(A)" - ] - }, - { - "cell_type": "markdown", - "id": "88a48c23", - "metadata": {}, - "source": [ - "- `mapreduce(f, op, array)`: Wende `f` auf alle Einträge an, dann reduziere mit `op`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4ea5e808", - "metadata": {}, - "outputs": [], - "source": [ - "mapreduce(x -> x^2, +, A ) # Summe der Quadrate aller Einträge" - ] - }, - { - "cell_type": "markdown", - "id": "f6373c3d", - "metadata": {}, - "source": [ - "- Gibt es Elemente in A, die > 5 sind? \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f3aac8eb", - "metadata": {}, - "outputs": [], - "source": [ - "any(x -> x>5, A) " - ] - }, - { - "cell_type": "markdown", - "id": "9e9df67c", - "metadata": {}, - "source": [ - "- Wieviele Elemente in A sind > 5?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8377529f", - "metadata": {}, - "outputs": [], - "source": [ - "count(x-> x>5, A) " - ] - }, - { - "cell_type": "markdown", - "id": "b3038478", - "metadata": {}, - "source": [ - "- sind alle Einträge positiv?\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "911556d1", - "metadata": {}, - "outputs": [], - "source": [ - "all(x-> x>0, A)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/9_functs.ipynb b/nb/9_functs.ipynb deleted file mode 100644 index b078712..0000000 --- a/nb/9_functs.ipynb +++ /dev/null @@ -1,1136 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "c68c2670", - "metadata": {}, - "source": [ - "# Funktionen und Operatoren\n", - "\n", - "Funktionen verarbeiten ihre Argumente zu einem Ergebnis, das sie beim Aufruf zurückliefern.\n", - "\n", - "## Formen\n", - "\n", - "Funktionen können in verschiedenen Formen definiert werden:\n", - "\n", - "I. Als `function ... end`-Block\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9443ccb7", - "metadata": {}, - "outputs": [], - "source": [ - "function hyp(x,y)\n", - " sqrt(x^2+y^2)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "50291f2a", - "metadata": {}, - "source": [ - "II. Als \"Einzeiler\" \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4657e421", - "metadata": {}, - "outputs": [], - "source": [ - "hyp(x, y) = sqrt(x^2 + y^2)" - ] - }, - { - "cell_type": "markdown", - "id": "d36c44e2", - "metadata": {}, - "source": [ - "III. Als anonyme Funktionen\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "02e66f6e", - "metadata": {}, - "outputs": [], - "source": [ - "(x, y) -> sqrt(x^2 + y^2)" - ] - }, - { - "cell_type": "markdown", - "id": "f3c09c53", - "metadata": {}, - "source": [ - "### Block-Form und `return`\n", - "\n", - "\n", - "- Mit `return` wird die Abarbeitung der Funktion beendet und zum aufrufenden Kontext zurückgekehrt.\n", - "- Ohne `return` wird der Wert des letzten Ausdrucks als Funktionswert zurückgegeben.\n", - "\n", - "Die beiden Definitionen\n", - "\n", - "```julia\n", - "function xsinrecipx(x)\n", - " if x == 0 \n", - " return 0.0\n", - " end \n", - " return x * sin(1/x)\n", - "end\n", - "```\n", - "und ohne das zweite explizite `return` in der letzten Zeile: \n", - "\n", - "```julia\n", - "function xsinrecipx(x)\n", - " if x == 0 \n", - " return 0.0\n", - " end \n", - " x * sin(1/x)\n", - "end\n", - "```\n", - "\n", - "sind also äquivalent.\n", - "\n", - "\n", - "- Eine Funktion, die \"nichts\" zurückgibt (_void functions_ in der C-Welt), gibt den Wert `nothing` vom Typ `Nothing` zurück. (So wie ein Objekt vom Typ `Bool` die beiden Werte `true` und `false` haben kann, so kann ein Objekt vom Typ `Nothing` nur einen einzigen Wert, eben `nothing`, annehmen.)\n", - "- Eine leere `return`-Anweisung ist äquivalent zu `return nothing`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6694b46d", - "metadata": {}, - "outputs": [], - "source": [ - "function fn(x)\n", - " println(x)\n", - " return \n", - "end\n", - "\n", - "a = fn(2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ee012edc", - "metadata": {}, - "outputs": [], - "source": [ - "a" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fca80289", - "metadata": {}, - "outputs": [], - "source": [ - "@show a typeof(a);" - ] - }, - { - "cell_type": "markdown", - "id": "39cf5d56", - "metadata": {}, - "source": [ - "### Einzeiler-Form\n", - "\n", - "Die Einzeilerform ist eine ganz normale Zuweisung, bei der links eine Funktion steht.\n", - "\n", - "```julia\n", - "hyp(x, y) = sqrt(x^2 + y^2)\n", - "```\n", - "\n", - "Julia kennt zwei Möglichkeiten, mehrere Anweisungen zu einem Block zusammenzufassen, der an Stelle einer Einzelanweisung stehen kann: \n", - "\n", - "- `begin ... end`-Block\n", - "- Eingeklammerte durch Semikolon getrennte Anweisungen.\n", - "\n", - "In beiden Fällen ist der Wert des Blockes der Wert der letzten Anweisung.\n", - "\n", - "Damit funktioniert auch\n", - "```julia\n", - "hyp(x, y) = (z = x^2; z += y^2; sqrt(z))\n", - "```\n", - "\n", - "und\n", - "```julia\n", - "hyp(x, y) = begin \n", - " z = x^2\n", - " z += y^2 \n", - " sqrt(z) \n", - " end\n", - "```\n", - "\n", - "### Anonyme Funktionen\n", - "\n", - "Anonyme FUnktionen kann man der Anonymität entreisen, indem man ihnen einen Namen zuweist. \n", - "```julia\n", - "hyp = (x,y) -> sqrt(x^2 + y^2)\n", - "```\n", - "Ihre eigentliche Anwendung ist aber im Aufruf einer *(higher order)* Funktion, die eine Funktion als Argument erwartet. \n", - "\n", - "Typische Anwendungen sind `map(f, collection)`, welches eine Funktion auf alle Elemente einer Kollektion anwendet. In Julia funktioniert auch `map(f(x,y), collection1, collection2)`:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "35a8bd70", - "metadata": {}, - "outputs": [], - "source": [ - "map( (x,y) -> sqrt(x^2 + y^2), [3, 5, 8], [4, 12, 15])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f8cec9b2", - "metadata": {}, - "outputs": [], - "source": [ - "map( x->3x^3, 1:8 )" - ] - }, - { - "cell_type": "markdown", - "id": "71388002", - "metadata": {}, - "source": [ - "Ein weiteres Beispiel ist `filter(test, collection)`, wobei ein Test eine Funktion ist, die ein `Bool` zurückgibt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "11d55610", - "metadata": {}, - "outputs": [], - "source": [ - "filter(x -> ( x%3 == 0 && x%5 == 0), 1:100 )" - ] - }, - { - "cell_type": "markdown", - "id": "36b2a20b", - "metadata": {}, - "source": [ - "## Argumentübergabe\n", - "\n", - "\n", - "- Beim Funktionsaufruf werden von den als Funktionsargumente zu übergebenden Objekten keine Kopien gemacht. Die Variablen in der Funktion verweisen auf die Originalobjekte. Julia nennt dieses Konzept _pass_by_sharing_. \n", - "- Funktionen können also ihre Argumente wirksam modifizieren, falls es sich um _mutable_ Objekte, wie z.B. `Vector`, `Array` handelt.\n", - "- Es ist eine Konvention in Julia, dass die Namen von solchen argumentmodifizierenden Funktionen mit einem Ausrufungszeichen enden. Weiterhin steht dann üblicherweise das Argument, das modifiziert wird, an erster Stelle und es ist auch der Rückgabewert der Funktion. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "650adea1", - "metadata": {}, - "outputs": [], - "source": [ - "V = [1, 2, 3]\n", - "\n", - "W = fill!(V, 17)\n", - " # '===' ist Test auf Identität\n", - "@show V W V===W; # V und W benennen dasselbe Objekt " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "49a771b3", - "metadata": {}, - "outputs": [], - "source": [ - "function fill_first!(V, x)\n", - " V[1] = x\n", - " return V \n", - "end \n", - "\n", - "U = fill_first!(V, 42)\n", - "\n", - "@show V U V===U;" - ] - }, - { - "cell_type": "markdown", - "id": "d0d2e303", - "metadata": {}, - "source": [ - "## Varianten von Funktionsargumenten\n", - "\n", - "- Es gibt Positionsargumente (1. Argument, 2. Argument, ....) und _keyword_-Argumente, die beim Aufruf durch ihren Namen angesprochen werden müssen. \n", - "- Sowohl Positions- als auch _keyword_-Argumente können _default_-Werte haben. Beim Aufruf können diese Argumente weggelassen werden.\n", - "- Die Reihenfolge der Deklaration muss sein:\n", - " 1. Positionsargumente ohne Defaultwert, \n", - " 2. Positionsargumente mit Defaultwert,\n", - " 3. --- Semikolon ---,\n", - " 4. kommagetrennte Liste der Keywordargumente (mit oder ohne Defaultwert) \n", - "- Beim Aufruf können _keyword_-Argumente an beliebigen Stellen in beliebiger Reihenfolge stehen. Man kann sie wieder durch ein Semikolon von den Positionsargumenten abtrennen, muss aber nicht.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5ec6f56a", - "metadata": {}, - "outputs": [], - "source": [ - "fa(x, y=42; a) = println(\"x=$x, y=$y, a=$a\")\n", - "\n", - "fa(6, a=4, 7)\n", - "fa(6, 7; a=4)\n", - "fa(a=-2, 6)" - ] - }, - { - "cell_type": "markdown", - "id": "4389ea71", - "metadata": {}, - "source": [ - "Eine Funktion nur mit _keyword_-Argumenten wird so deklariert:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0fc2aeac", - "metadata": {}, - "outputs": [], - "source": [ - "fkw(; x=10, y) = println(\"x=$x, y=$y\")\n", - "\n", - "fkw(y=2)" - ] - }, - { - "cell_type": "markdown", - "id": "26e02ff2", - "metadata": {}, - "source": [ - "## Funktionen sind ganz normale Objekte\n", - "\n", - " - Sie können zugewiesen werden\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "17b38616", - "metadata": {}, - "outputs": [], - "source": [ - "f2 = sqrt\n", - "f2(2)" - ] - }, - { - "cell_type": "markdown", - "id": "325c567b", - "metadata": {}, - "source": [ - "- Sie können als Argumente an Funktionen übergeben werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4d5be6cf", - "metadata": {}, - "outputs": [], - "source": [ - "# sehr naive numerische Integration\n", - "\n", - "function Riemann_integrate(f, a, b; NInter=1000)\n", - " delta = (b-a)/NInter\n", - " s = 0\n", - " for i in 0:NInter-1\n", - " s += delta * f(a + delta/2 + i * delta)\n", - " end\n", - " return s\n", - "end\n", - "\n", - "\n", - "Riemann_integrate(sin, 0, π)" - ] - }, - { - "cell_type": "markdown", - "id": "43f02a36", - "metadata": {}, - "source": [ - "- Sie können von Funktionen erzeugt und als Ergebnis `return`t werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "81e0ad89", - "metadata": {}, - "outputs": [], - "source": [ - "function generate_add_func(x)\n", - " function addx(y)\n", - " return x+y\n", - " end\n", - " return addx\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5491730c", - "metadata": {}, - "outputs": [], - "source": [ - "h = generate_add_func(4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f39aa8b1", - "metadata": {}, - "outputs": [], - "source": [ - "h(1)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4b708a03", - "metadata": {}, - "outputs": [], - "source": [ - "h(2), h(10)" - ] - }, - { - "cell_type": "markdown", - "id": "5c0d6771", - "metadata": {}, - "source": [ - "Die obige Funktion `generate_add_func()` lässt sich auch kürzer definieren. Der innere Funktionsname `addx()` ist sowieso lokal und außerhalb nicht verfügbar. Also kann man eine anonyme Funktion verwenden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7817f2ff", - "metadata": {}, - "outputs": [], - "source": [ - "generate_add_func(x) = y -> x + y" - ] - }, - { - "cell_type": "markdown", - "id": "0cf5d3c0", - "metadata": {}, - "source": [ - "## Zusammensetzung von Funktionen: die Operatoren $\\circ$ und `|>`\n", - "\n", - "- Die Zusammensetzung _(composition)_ von Funktionen kann auch mit dem Operator $\\circ$ (`\\circ + Tab`) geschrieben werden \n", - "\n", - "$$(f\\circ g)(x) = f(g(x))$$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cae2ce88", - "metadata": {}, - "outputs": [], - "source": [ - "(sqrt ∘ + )(9, 16)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a16fb3c6", - "metadata": {}, - "outputs": [], - "source": [ - "f = cos ∘ sin ∘ (x->2x)\n", - "f(.2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ed8ec445", - "metadata": {}, - "outputs": [], - "source": [ - "@show map(uppercase ∘ first, [\"ein\", \"paar\", \"grüne\", \"Blätter\"]);" - ] - }, - { - "cell_type": "markdown", - "id": "6c6d5a5a", - "metadata": {}, - "source": [ - "- Es gibt auch einen Operator, mit dem Funktionen \"von rechts\" wirken und zusammengesetzt werden können _(piping)_\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d32aaa8f", - "metadata": {}, - "outputs": [], - "source": [ - "25 |> sqrt" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c5b9236a", - "metadata": {}, - "outputs": [], - "source": [ - "1:10 |> sum |> sqrt" - ] - }, - { - "cell_type": "markdown", - "id": "2af53243", - "metadata": {}, - "source": [ - "- Natürlich kann man auch diese Operatoren 'broadcasten' (s. @sec-broadcast). Hier wirkt ein Vektor von Funktionen elementweise auf einen Vektor von Argumenten:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4ea2ad9f", - "metadata": {}, - "outputs": [], - "source": [ - "[\"a\", \"list\", \"of\", \"strings\"] .|> [length, uppercase, reverse, titlecase]" - ] - }, - { - "cell_type": "markdown", - "id": "f941ceb5", - "metadata": {}, - "source": [ - "## Die `do`-Notation\n", - "\n", - "Eine syntaktische Besonderheit zur Definition anonymer Funktionen als Argumente anderer Funktionen ist die `do`-Notation.\n", - "\n", - "Sei `higherfunc(f,a,...)` eine Funktion, deren 1. Argument eine Funktion ist. \n", - "\n", - "Dann kann man `higherfunc()` auch ohne erstes Argument aufrufen und statt dessen die Funktion in einem unmittelbar folgenden `do`-Block definieren:\n", - "\n", - "```julia\n", - "higherfunc(a, b) do x, y\n", - " Körper von f(x,y)\n", - "end\n", - "```\n", - "\n", - "Am Beispiel von `Riemann_integrate()` sieht das so aus:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a6620e38", - "metadata": {}, - "outputs": [], - "source": [ - "# das ist dasselbe wie Riemann_integrate(x->x^2, 0, 2)\n", - "\n", - "Riemann_integrate(0, 2) do x x^2 end" - ] - }, - { - "cell_type": "markdown", - "id": "26486b16", - "metadata": {}, - "source": [ - "Der Sinn besteht natürlich in der Anwendung mit komplexeren Funktionen, wie diesem aus zwei Teilstücken zusammengesetzten Integranden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "53714315", - "metadata": {}, - "outputs": [], - "source": [ - "r = Riemann_integrate(0, π) do x\n", - " z1 = sin(x)\n", - " z2 = log(1+x)\n", - " if x > 1 \n", - " return z1^2\n", - " else\n", - " return 1/z2^2\n", - " end\n", - " end" - ] - }, - { - "cell_type": "markdown", - "id": "c973f2c1", - "metadata": {}, - "source": [ - "## Funktionsartige Objekte\n", - "\n", - "Durch Definition einer geeigneten Methode für einen Typ kann man beliebige Objekte *callable* machen, d.h., sie anschließend wie Funktionen aufrufen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "73cc94fd", - "metadata": {}, - "outputs": [], - "source": [ - "# struct speichert die Koeffiziente eines Polynoms 2. Grades\n", - "struct Poly2Grad \n", - " a0::Float64\n", - " a1::Float64\n", - " a2::Float64\n", - "end\n", - "\n", - "p1 = Poly2Grad(2,5,1)\n", - "p2 = Poly2Grad(3,1,-0.4)" - ] - }, - { - "cell_type": "markdown", - "id": "99427b65", - "metadata": {}, - "source": [ - "Die folgende Methode macht diese Struktur `callable`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "94bbfd15", - "metadata": {}, - "outputs": [], - "source": [ - "function (p::Poly2Grad)(x)\n", - " p.a2 * x^2 + p.a1 * x + p.a0\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "b13ba4a8", - "metadata": {}, - "source": [ - "Jetzt kann man die Objekte, wenn gewünscht, auch wie Funktionen verwenden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9b490828", - "metadata": {}, - "outputs": [], - "source": [ - "@show p2(5) p1(-0.7) p1;" - ] - }, - { - "cell_type": "markdown", - "id": "bff0bff7", - "metadata": {}, - "source": [ - "## Operatoren und spezielle Formen\n", - "\n", - "- Infix-Operatoren wie `+,*,>,∈,...` sind Funktionen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "da10ff9f", - "metadata": {}, - "outputs": [], - "source": [ - "+(3, 7)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "177a174d", - "metadata": {}, - "outputs": [], - "source": [ - "f = +" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f0f52152", - "metadata": {}, - "outputs": [], - "source": [ - "f(3, 7)" - ] - }, - { - "cell_type": "markdown", - "id": "39178d6d", - "metadata": {}, - "source": [ - "- Auch Konstruktionen wie `x[i]`, `a.x`, `[x; y]` werden vom Parser zu Funktionsaufrufen umgewandelt.\n", - "\n", - ":::{.narrow}\n", - "\n", - "| | |\n", - "| :-: | :------------ |\n", - "| x[i] | getindex(x, i) |\n", - "| x[i] = z | setindex!(x, z, i) |\n", - "| a.x | getproperty(a, :x) | \n", - "| a.x = z | setproperty!(a, :x, z) |\n", - "| [x; y;...] | vcat(x, y, ...) |\n", - " :Spezielle Formen [(Auswahl)](https://docs.julialang.org/en/v1/manual/functions/#Operators-With-Special-Names)\n", - "\n", - ":::\n", - "\n", - "(Der Doppelpunkt vor einer Variablen macht diese zu einem Symbol.)\n", - "\n", - ":::{.callout-note}\n", - "Für diese Funktionen kann man eigene Methoden implementieren. Zum Beispiel könnten bei einem eigenen Typ das Setzen eines Feldes (`setproperty!()`) die Gültigkeit des Wertes prüfen oder weitere Aktionen veranlassen. \n", - "\n", - "Prinzipiell können `get/setproperty` auch Dinge tun, die gar nichts mit einem tatsächlich vorhandenen Feld der Struktur zu tun haben. \n", - ":::\n", - "\n", - "## Update-Form\n", - "\n", - "Alle arithmetischen Infix-Operatoren haben eine update-Form: Der Ausdruck\n", - "```julia\n", - "x = x ⊙ y\n", - "```\n", - "kann auch geschrieben werden als\n", - "```julia\n", - "x ⊙= y\n", - "```\n", - "\n", - "Beide Formen sind semantisch äquivalent. Insbesondere wird in beiden Formen der Variablen `x` ein auf der rechten Seite geschaffenes neues Objekt zugewiesen. \n", - "\n", - "Ein Speicherplatz- und Zeit-sparendes __in-place-update__ eines Arrays/Vektors/Matrix ist möglich entweder durch explizite Indizierung\n", - "```julia\n", - "for i in eachindex(x)\n", - " x[i] += y[i]\n", - "end\n", - "```\n", - "oder durch die dazu semantisch äquivalente _broadcast_-Form (s. @sec-broadcast):\n", - "```julia\n", - "x .= x .+ y\n", - "```\n", - "\n", - "\n", - "\n", - "## Vorrang und Assoziativität von Operatoren {#sec-vorrang}\n", - "\n", - "Zu berechnende Ausdrücke \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "419bcd07", - "metadata": {}, - "outputs": [], - "source": [ - " -2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2" - ] - }, - { - "cell_type": "markdown", - "id": "3b37d178", - "metadata": {}, - "source": [ - "werden vom Parser in eine Baumstruktur überführt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7e5bd52c", - "metadata": {}, - "outputs": [], - "source": [ - "using TreeView\n", - "\n", - "walk_tree(Meta.parse(\"-2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2\"))" - ] - }, - { - "cell_type": "markdown", - "id": "d26e9cbc", - "metadata": {}, - "source": [ - "- Die Auswertung solcher Ausdrücke wird durch \n", - " - Vorrang _(precedence)_ und \n", - " - Assoziativität geregelt.\n", - "- 'Vorrang' definiert, welche Operatoren stärker binden im Sinne von \"Punktrechnung geht vor Strichrechnung\".\n", - "- 'Assoziativität' bestimmt die Auswertungsreihenfolge bei gleichen oder gleichrangigen Operatoren.\n", - "- [Vollständige Dokumentation](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Operator-Precedence-and-Associativity)\n", - "\n", - "### Assoziativität\n", - "\n", - "Sowohl Addition und Subtraktion als auch Multiplikation und Divison sind jeweils gleichrangig und linksassoziativ, d.h. es wird von links ausgewertet.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3faed089", - "metadata": {}, - "outputs": [], - "source": [ - "200/5/2 # wird von links ausgewertet als (200/5)/2 " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "559f6beb", - "metadata": {}, - "outputs": [], - "source": [ - "200/2*5 # wird von links ausgewertet als (200/2)*5" - ] - }, - { - "cell_type": "markdown", - "id": "115f7493", - "metadata": {}, - "source": [ - "Zuweisungen wie `=`, `+=`, `*=`,... sind gleichrangig und rechtsassoziativ.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "72456757", - "metadata": {}, - "outputs": [], - "source": [ - "x = 1\n", - "y = 10\n", - "\n", - "# wird von rechts ausgewertet: x += (y += (z = (a = 20)))\n", - "\n", - "x += y += z = a = 20 \n", - "\n", - "@show x y z a;" - ] - }, - { - "cell_type": "markdown", - "id": "a716bc08", - "metadata": {}, - "source": [ - "Natürlich kann man die Assoziativität in Julia auch abfragen. Die entsprechenden Funktionen werden nicht explizit aus dem `Base`-Modul exportiert, deshalb muss man den Modulnamen beim Aufruf angeben. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f2317e6a", - "metadata": {}, - "outputs": [], - "source": [ - "for i in (:/, :+=, :(=), :^)\n", - " a = Base.operator_associativity(i)\n", - " println(\"Operation $i is $(a)-assoziative\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "3a7e3a79", - "metadata": {}, - "source": [ - "Also ist der Potenzoperator rechtsassoziativ.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "21fe9789", - "metadata": {}, - "outputs": [], - "source": [ - "2^3^2 # rechtsassoziativ, = 2^(3^2) " - ] - }, - { - "cell_type": "markdown", - "id": "0d333e68", - "metadata": {}, - "source": [ - "### Vorrang\n", - "\n", - "- Julia ordnet den Operatoren Vorrangstufen von 1 bis 17 zu: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e5ad39a5", - "metadata": {}, - "outputs": [], - "source": [ - "for i in (:+, :-, :*, :/, :^, :(=))\n", - " p = Base.operator_precedence(i)\n", - " println(\"Vorrang von $i = $p\") \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "4decdf33", - "metadata": {}, - "source": [ - "- 11 ist kleiner als 12, also geht 'Punktrechnung vor Strichrechnung'\n", - "- Der Potenz-Operator `^` hat eine höhere _precedence_.\n", - "- Zuweisungen haben die kleinste _precedence_\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9450f974", - "metadata": {}, - "outputs": [], - "source": [ - "# Zuweisung hat kleinsten Vorrang, daher Auswertung als x = (3 < 4)\n", - "\n", - "x = 3 < 4 \n", - "x" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d631e121", - "metadata": {}, - "outputs": [], - "source": [ - "(y = 3) < 4 # Klammern schlagen natürlich jeden Vorrang\n", - "y" - ] - }, - { - "cell_type": "markdown", - "id": "0969d330", - "metadata": {}, - "source": [ - "Nochmal zum Beispiel vom Anfang von @sec-vorrang:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "107124d7", - "metadata": {}, - "outputs": [], - "source": [ - "-2^3+500/2/10==8 && 13 > 7 + 1 || 9 < 2" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "420964a2", - "metadata": {}, - "outputs": [], - "source": [ - "for i ∈ (:^, :+, :/, :(==), :&&, :>, :|| )\n", - " print(i, \" \")\n", - " println(Base.operator_precedence(i))\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "9c17c3e7", - "metadata": {}, - "source": [ - "Nach diesen Vorrangregeln wird der Beispielausdruck also wie folgt ausgewertet:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "43b21b33", - "metadata": {}, - "outputs": [], - "source": [ - "((-(2^3)+((500/2)/10)==8) && (13 > (7 + 1))) || (9 < 2)" - ] - }, - { - "cell_type": "markdown", - "id": "2d52102a", - "metadata": {}, - "source": [ - "(Das entspricht natürlich dem oben gezeigten *parse-tree*)\n", - "\n", - "Es gilt also für den Vorrang:\n", - "\n", - "> Potenz > Multiplikation/Division > Addition/Subtraktion > Vergleiche > logisches && > logisches || > Zuweisung\n", - "\n", - "Damit wird ein Ausdruck wie \n", - "```julia\n", - " a = x <= y + z && x > z/2 \n", - "``` \n", - "sinnvoll ausgewertet als `a = ((x <= (y+z)) && (x < (z/2)))`\n", - "\n", - "\n", - "- Eine Besonderheit sind noch\n", - " \n", - " - unäre Operatoren, also insbesondere `+` und `-` als Vorzeichen \n", - " - _juxtaposition_, also Zahlen direkt vor Variablen oder Klammern ohne `*`-Symbol\n", - " \n", - " Beide haben Vorrang noch vor Multiplikation und Division. \n", - "\n", - ":::{.callout-important}\n", - "Damit ändert sich die Bedeutung von Ausdrücken, wenn man _juxtaposition_ anwendet:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a4465163", - "metadata": {}, - "outputs": [], - "source": [ - "1/2*π, 1/2π" - ] - }, - { - "cell_type": "markdown", - "id": "1529af73", - "metadata": {}, - "source": [ - "::: \n", - " \n", - "- Im Vergleich zum Potenzoperator `^` gilt (s. [https://discourse.julialang.org/t/confused-about-operator-precedence-for-2-3x/8214/7](https://discourse.julialang.org/t/confused-about-operator-precedence-for-2-3x/8214/7) ):\n", - " \n", - " > Unary operators, including juxtaposition, bind tighter than ^ on the right but looser on the left.\n", - "\n", - "Beispiele:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8dbccf82", - "metadata": {}, - "outputs": [], - "source": [ - "-2^2 # -(2^2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "26415d53", - "metadata": {}, - "outputs": [], - "source": [ - "x = 5\n", - "2x^2 # 2(x^2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b07aabae", - "metadata": {}, - "outputs": [], - "source": [ - "2^-2 # 2^(-2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "09f3ecc4", - "metadata": {}, - "outputs": [], - "source": [ - "2^2x # 2^(2x)" - ] - }, - { - "cell_type": "markdown", - "id": "d1e4bc70", - "metadata": {}, - "source": [ - "- Funktionsanwendung `f(...)` hat Vorrang vor allen Operatoren\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a9c32959", - "metadata": {}, - "outputs": [], - "source": [ - "sin(x)^2 === (sin(x))^2 # nicht sin(x^2)" - ] - }, - { - "cell_type": "markdown", - "id": "e9915990", - "metadata": {}, - "source": [ - "### Zusätzliche Operatoren\n", - "\n", - "Der [Julia-Parser](https://github.com/JuliaLang/julia/blob/master/src/julia-parser.scm#L13-L31) definiert für zahlreiche Unicode-Zeichen einen Vorrang auf Vorrat, so dass diese Zeichen von Paketen und selbstgeschriebenem Code als Operatoren benutzt werden können. \n", - "\n", - "So haben z.B.\n", - "```julia\n", - " ∧ ⊗ ⊘ ⊙ ⊚ ⊛ ⊠ ⊡ ⊓ ∗ ∙ ∤ ⅋ ≀ ⊼ ⋄ ⋆ ⋇ ⋉ ⋊ ⋋ ⋌ ⋏ ⋒ ⟑ ⦸ ⦼ ⦾ ⦿ ⧶ ⧷ ⨇ ⨰ ⨱ ⨲ ⨳ ⨴ ⨵ ⨶ ⨷ ⨸ ⨻ ⨼ ⨽ ⩀ ⩃ ⩄ ⩋ ⩍ ⩎ ⩑ ⩓ ⩕ ⩘ ⩚ ⩜ ⩞ ⩟ ⩠ ⫛\n", - "```\n", - "\n", - "den Vorrang 12 wie Multiplikation/Division (und sind wie diese linksassoziativ) \n", - "und z.B.\n", - "```julia\n", - " ⊕ ⊖ ⊞ ⊟ |++| ∪ ∨ ⊔ ± ∓ ∔ ∸ ≏ ⊎ ⊻ ⊽ ⋎ ⋓ ⧺ ⧻ ⨈ ⨢ ⨣ ⨤ ⨥ ⨦ ⨧ ⨨ ⨩ ⨪ ⨫ ⨬ ⨭ ⨮ ⨹ ⨺ ⩁ ⩂ ⩅ ⩊ ⩌ ⩏ ⩐ ⩒ ⩔ ⩖ ⩗ \n", - "```\n", - "haben den Vorrang 11 wie Addition/Subtraktion.\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/Erste_Bsp.ipynb b/nb/Erste_Bsp.ipynb deleted file mode 100644 index 83ce8e0..0000000 --- a/nb/Erste_Bsp.ipynb +++ /dev/null @@ -1,341 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "f21dc71b", - "metadata": {}, - "source": [ - "# Erste Miniprogramme\n", - "\n", - "\n", - "## Was sollte man zum Programmieren können?\n", - "\n", - "\n", - "- **Denken in Algorithmen:** \n", - " Welche Schritte sind zur Lösung des Problems nötig? Welche Daten müssen gespeichert, welche Datenstrukturen angelegt werden? Welche Fälle können auftreten und müssen erkannt und behandelt werden? \n", - "- **Umsetzung des Algorithmus in ein Programm:** \n", - " Welche Datenstrukturen, Konstrukte, Funktionen... stellt die Programmiersprache bereit? \n", - "- **Formale Syntax:** \n", - " Menschen verstehen 'broken English'; Computer verstehen kein 'broken C++' oder 'broken Julia'. Die Syntax muss beherrscht werden.\n", - "- **„Ökosystem“ der Sprache:** \n", - " Wie führe ich meinen Code aus? Wie funktionieren die Entwicklungsumgebungen? Welche Optionen versteht der Compiler? Wie installiere ich Zusatzbibliotheken? Wie lese ich Fehlermeldungen? Wo kann ich mich informieren? \n", - "- **die Kunst des Debugging:** \n", - " Programmieranfänger sind oft glücklich, wenn sie alle Syntaxfehler eliminiert haben und das Programm endlich 'durchläuft'. Bei komplexeren Programmen fängt die Arbeit jetzt erst an, denn nun muss getestet und die Fehler im Algorithmus gefunden und behoben werden. \n", - "- **Gefühl für die Effizienz und Komplexität von Algorithmen**\n", - "- **Besonderheiten der Computerarithmetik**, insbesondere der Gleitkommazahlen\n", - "\n", - "Das erschließt sich nicht alles auf einmal. Haben Sie Geduld mit sich und 'spielen' Sie mit der Sprache. \n", - "\n", - "Das Folgende soll eine kleine Anregung dazu sein.\n", - "\n", - "## Project Euler\n", - "\n", - "Eine hübsche Quelle für Programmieraufgaben mit mathematischem Charakter und sehr unterschiedlichen Schwierigkeitsgraden ist [Project Euler](https://projecteuler.net/). \n", - "Die Aufgaben sind so gestaltet, dass keinerlei Eingaben notwendig und das gesuchte Ergebnis eine einzige Zahl ist. So kann man sich voll auf das Programmieren des Algorithmus konzentrieren. \n", - "\n", - "---------\n", - "\n", - "### Beispiel 1\n", - "\n", - "::::::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "https://github.com/luckytoilet/projecteuler-solutions/blob/master/Solutions.md\n", - "https://math.stackexchange.com/questions/3370978/iterating-sum-of-squares-of-decimal-digits-of-an-integer-how-big-can-it-grow\n", - "aufg. 92\n", - "\n", - ":::\n", - "\n", - "::: {.callout-note icon=false .titlenormal}\n", - "## Project Euler Problem No 1\n", - "\n", - "If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.\n", - "\n", - "Find the sum of all the multiples of 3 or 5 below 1000.\n", - "\n", - ":::\n", - "\n", - "1. Algorithmus: \n", - " - Teste alle natürlichen Zahlen <1000 auf Teilbarkeit durch 3 oder durch 5 und\n", - " - summiere die teilbaren Zahlen auf.\n", - "\n", - "2. Umsetzung:\n", - "\n", - " Wie liefert Julia den Rest der Ganzzahldivision? Solche Funktionen heißen typischerweise `rem()` (für *remainder*) oder `mod()`. [Nachlesen in der Doku](https://docs.julialang.org/en/v1/base/math/#Base.rem) oder ausprobieren von `?rem` und `?mod` in der Julia-REPL zeigt, dass es beides gibt. Der Unterschied liegt in der Behandlung negativer ganzer Zahlen. Für natürliche Zahlen `n,m` liefern `mod(n,m)` und `rem(n,m)` dasselbe und letzteres hat auch noch die Infix-Form `n % m`. \n", - " \n", - " Wie testet man eine Reihe von Werten durch und summiert auf? Da gibt es ein Standardmuster: `for`-Schleife und Akkumulatorvariable: \n", - "\n", - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "\n", - "## Eine Lösungsvariante:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "44d0f59e", - "metadata": {}, - "outputs": [], - "source": [ - "s = 0 # Akkumulatorvariable initialisieren\n", - "for i in 1:999 # Schleife \n", - " if i % 3 == 0 || i % 5 == 0 # Test\n", - " s += i # Zu Akkumulator addieren \n", - " end # Ende Test\n", - "end # Ende Schleife\n", - "println(\" Die Antwort ist: $s\") # Ausgabe des Ergebnisses " - ] - }, - { - "cell_type": "markdown", - "id": "4d9f5b4f", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "Natürlich geht das auch etwas kürzer:\n", - "\n", - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "\n", - "## Noch eine Lösungsvariante:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9d36a90d", - "metadata": {}, - "outputs": [], - "source": [ - "sum([i for i in 1:999 if i%3==0||i%5==0])" - ] - }, - { - "cell_type": "markdown", - "id": "71a52de7", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "\n", - "-----------\n", - "\n", - "### Beispiel 2\n", - "\n", - "\n", - "::: {.callout-note icon=false .titlenormal}\n", - "## Project Euler Problem No 92\n", - "A number chain is created by continuously adding the square of the digits in a number to form a new number until it has been seen before.\n", - "\n", - "For example,\n", - "\n", - "| 44 → 32 → 13 → 10 → **1** → **1**\n", - "| 85 → **89** → 145 → 42 → 20 → 4 → 16 → 37 → 58 → **89**\n", - "\n", - "Therefore any chain that arrives at 1 or 89 will become stuck in an endless loop. What is most amazing is that EVERY starting number will eventually arrive at 1 or 89.\n", - "\n", - "How many starting numbers below ten million will arrive at 89?\n", - ":::\n", - "\n", - "Programme kann man [*top-down* und *bottom-up*](https://de.wikipedia.org/wiki/Top-Down-_und_Bottom-Up-Design) entwickeln.\n", - "*Top-down* würde hier wohl bedeuten: „Wir fangen mit einer Schleife `for i = 1:9999999` an.“ Der andere Weg führt über einzeln testbare Komponenten und ist oft zielführender. (Und ab einer gewissen Projektgröße nähert man sich sowieso von 'top' und 'bottom' gleichzeitig dem Ziel.)\n", - "\n", - "##### Funktion Nr. 1\n", - "Es soll untersucht werden, wie sich die Zahlen unter dem wiederholten Berechnen der 'Quadratquersumme' (Summe der Quadrate der Ziffern) verhalten. Also sollte man eine Funktion schreiben und testen, die diese 'Quadratquersumme' berechnet. \n", - "\n", - "\n", - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "\n", - "## `q2sum(n)` berechnet die Summe der Quadrate der Ziffern von n im Dezimalsystem:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "15983324", - "metadata": {}, - "outputs": [], - "source": [ - "#| output: false\n", - "function q2sum(n)\n", - " s = 0 # Akkumulator für die Summe\n", - " while n > 9 # solange noch mehrstellig...\n", - " q, r = divrem(n, 10) # berechne Ganzzahlquotient und Rest bei Division durch 10\n", - " s += r^2 # addiere quadrierte Ziffer zum Akkumulator\n", - " n = q # mache weiter mit der durch 10 geteilten Zahl\n", - " end\n", - " s += n^2 # addiere das Quadrat der letzten Ziffer\n", - " return s\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "7cafe59e", - "metadata": {}, - "source": [ - ":::\n", - "... und das testen wir jetzt natürlich:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "82139e32", - "metadata": {}, - "outputs": [], - "source": [ - "for i in [1, 7, 33, 111, 321, 1000, 73201]\n", - " j = q2sum(i)\n", - " println(\"Quadratquersumme von $i = $j\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "1467ade0", - "metadata": {}, - "source": [ - "Im Sinne der Aufgabe wenden wir die Funktion wiederholt an:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2a91c9da", - "metadata": {}, - "outputs": [], - "source": [ - "n = 129956799\n", - "for i in 1:14\n", - " n = q2sum(n)\n", - " println(n)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "1399219b", - "metadata": {}, - "source": [ - "... und haben hier einen der '89er Zyklen' getroffen.\n", - "\n", - "\n", - "#### Funktion Nr. 2\n", - "\n", - "Wir müssen testen, ob die wiederholte Anwendung der Funktion `q2sum()` schließlich zu **1** führt oder in diesem **89er**-Zyklus endet.\n", - "\n", - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "\n", - "## `q2test(n)` ermittelt, ob wiederholte Quadratquersummenbildung in den 89er-Zyklus führt:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8b76324d", - "metadata": {}, - "outputs": [], - "source": [ - "#| output: false\n", - "function q2test(n)\n", - " while n !=1 && n != 89 # solange wir nicht bei 1 oder 89 angekommen sind....\n", - " n = q2sum(n) # wiederholen \n", - " end\n", - " if n==1 return false end # keine 89er-Zahl\n", - " return true # 89er-Zahl gefunden\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "06d73770", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "... und damit können wir die Aufgabe lösen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7a0051f2", - "metadata": {}, - "outputs": [], - "source": [ - "c = 0 # mal wieder ein Akkumulator\n", - "for i = 1 : 10_000_000 - 1 # so kann man in Julia Tausenderblöcke zur besseren Lesbarkeit abtrennen\n", - " if q2test(i) # q2test() gibt einen Boolean zurück, kein weiterer Test nötig \n", - " c += 1 # 'if x == true' ist redundant, 'if x' reicht völlig \n", - " end \n", - "end\n", - "println(\"$c numbers below ten million arrive at 89.\")" - ] - }, - { - "cell_type": "markdown", - "id": "000b5826", - "metadata": {}, - "source": [ - "Zahlen, bei denen die iterierte Quadratquersummenbildung bei 1 endet, heißen übrigens [fröhliche Zahlen](https://de.wikipedia.org/wiki/Fr%C3%B6hliche_Zahl) und wir haben gerade die Anzahl der traurigen Zahlen kleiner als 10.000.000 berechnet.\n", - "\n", - "Hier nochmal das vollständige Programm:\n", - "\n", - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "## unsere Lösung von Project Euler No 92:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "db3ef4ef", - "metadata": {}, - "outputs": [], - "source": [ - "function q2sum(n)\n", - " s = 0 \n", - " while n > 9 \n", - " q, r = divrem(n, 10)\n", - " s += r^2 \n", - " n = q \n", - " end\n", - " s += n^2 \n", - " return s\n", - "end\n", - "\n", - "function q2test(n)\n", - " while n !=1 && n != 89 \n", - " n = q2sum(n) \n", - " end\n", - " if n==1 return false end \n", - " return true \n", - "end\n", - "\n", - "c = 0\n", - "for i = 1 : 10_000_000 - 1 \n", - " if q2test(i)\n", - " c += 1\n", - " end \n", - "end\n", - "println(\"$c numbers below ten million arrive at 89.\")" - ] - }, - { - "cell_type": "markdown", - "id": "8d2084be", - "metadata": {}, - "source": [ - ":::" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/Pi.ipynb b/nb/Pi.ipynb deleted file mode 100644 index d81ece9..0000000 --- a/nb/Pi.ipynb +++ /dev/null @@ -1,233 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "0b96655f", - "metadata": {}, - "source": [ - "# Ein Beispiel zur Stabilität von Gleitkommaarithmetik\n", - "\n", - "## Berechnung von $\\pi$ nach Archimedes\n", - "\n", - "\n", - "\n", - "Eine untere Schranke für $2\\pi$, den Umfang des Einheitskreises, erhält man durch die\n", - "Summe der Seitenlängen eines dem Einheitskreis eingeschriebenen regelmäßigen $n$-Ecks.\n", - " Die Abbildung links zeigt, wie man beginnend mit einem Viereck der Seitenlänge $s_4=\\sqrt{2}$ die Eckenzahl iterativ verdoppelt.\n", - "\n", - "| Abb. 1 | Abb.2 |\n", - "| :-: | :-: |\n", - "| ![](../images/pi1.png) | ![](../images/pi2.png) |\n", - "\n", - "Die zweite Abbildung zeigt die Geometrie der Eckenverdoppelung.\n", - "\n", - "Mit\n", - "$|\\overline{AC}|= s_{n},\\quad |\\overline{AB}|= |\\overline{BC}|= s_{2n},\\quad |\\overline{MN}| =a, \\quad |\\overline{NB}| =1-a,$ liefert Pythagoras für die Dreiecke $MNA$ und\n", - " $NBA$ jeweils\n", - "$$\n", - " a^2 + \\left(\\frac{s_{n}}{2}\\right)^2 = 1\\qquad\\text{bzw.} \\qquad\n", - " (1-a)^2 + \\left(\\frac{s_{n}}{2}\\right)^2 = s_{2n}^2\n", - "$$\n", - "Elimination von $a$ liefert die Rekursion\n", - "$$\n", - " s_{2n} = \\sqrt{2-\\sqrt{4-s_n^2}} \\qquad\\text{mit Startwert}\\qquad\n", - " s_4=\\sqrt{2}\n", - "$$\n", - "für die Länge $s_n$ **einer** Seite des eingeschriebenen regelmäßigen\n", - "$n$-Ecks.\n", - "\n", - "\n", - "Die Folge $(n\\cdot s_n)$\n", - "konvergiert monoton von unten gegen den\n", - "Grenzwert $2\\pi$:\n", - "$$\n", - " n\\, s_n \\rightarrow 2\\pi % \\qquad\\text{und} \\qquad {n c_n}\\downarrow 2\\pi\n", - "$$\n", - "Der relative Fehler der Approximation von 2π durch ein $n$-Eck ist:\n", - "$$\n", - " \\epsilon_n = \\left| \\frac{n\\, s_n-2 \\pi}{2\\pi} \\right|\n", - "$$\n", - "\n", - "\n", - "## Zwei Iterationsvorschriften^[nach: Christoph Überhuber, „Computer-Numerik“ Bd. 1, Springer 1995, Kap. 2.3]\n", - "Die Gleichung\n", - "$$\n", - " s_{2n} = \\sqrt{2-\\sqrt{4-s_n^2}}\\qquad \\qquad \\textrm{(Iteration A)}\n", - "$$\n", - "ist mathematisch äquivalent zu\n", - "$$\n", - " s_{2n} = \\frac{s_n}{\\sqrt{2+\\sqrt{4-s_n^2}}} \\qquad \\qquad \\textrm{(Iteration B)}\n", - "$$\n", - "\n", - "(Bitte nachrechnen!) \n", - "\n", - "\n", - "\n", - "Allerdings ist Iteration A schlecht konditioniert und numerisch instabil, wie der folgende Code zeigt. Ausgegeben wird die jeweils berechnete Näherung für π.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fa3be89a", - "metadata": {}, - "outputs": [], - "source": [ - "using Printf\n", - "\n", - "iterationA(s) = sqrt(2 - sqrt(4 - s^2))\n", - "iterationB(s) = s / sqrt(2 + sqrt(4 - s^2))\n", - "\n", - "s_B = s_A = sqrt(2) # Startwert \n", - "\n", - "ϵ(x) = abs(x - 2π)/2π # rel. Fehler \n", - "\n", - "ϵ_A = Float64[] # Vektoren für den Plot\n", - "ϵ_B = Float64[]\n", - "is = Float64[]\n", - "\n", - "@printf \"\"\" approx. Wert von π\n", - " n-Eck Iteration A Iteration B\n", - "\"\"\"\n", - "\n", - "for i in 3:35\n", - " push!(is, i)\n", - " s_A = iterationA(s_A) \n", - " s_B = iterationB(s_B) \n", - " doublePi_A = 2^i * s_A\n", - " doublePi_B = 2^i * s_B\n", - " push!(ϵ_A, ϵ(doublePi_A))\n", - " push!(ϵ_B, ϵ(doublePi_B))\n", - " @printf \"%14i %20.15f %20.15f\\n\" 2^i doublePi_A/2 doublePi_B/2 \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "7ce50a85", - "metadata": {}, - "source": [ - "Während Iteration B sich stabilisiert bei einem innerhalb der Maschinengenauigkeit korrekten Wert für π, wird Iteration A schnell instabil. Ein Plot der relativen Fehler $\\epsilon_i$ bestätigt das:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5004b70e", - "metadata": {}, - "outputs": [], - "source": [ - "using CairoMakie\n", - "\n", - "F = Figure(resolution=(800,500))\n", - "ax = Axis(F[1, 1], xlabel = \"Iterationsschritte\", ylabel = \"rel. Fehler\",\n", - " yscale = log10, xticks=2:2:35, yticks=LogTicks(-20:0))\n", - "\n", - "scatterlines!(ax, is, ϵ_A, label = \"Iteration A\" )\n", - "scatterlines!(ax, is, ϵ_B, marker=:xcross, label = \"Iteration B\" )\n", - "\n", - "axislegend(position=:rc)\n", - "F" - ] - }, - { - "cell_type": "markdown", - "id": "7a93c5e3", - "metadata": {}, - "source": [ - "## Stabilität und Auslöschung\n", - "\n", - "Bei $i=26$ erreicht Iteration B einen relativen Fehler in der Größe des Maschinenepsilons:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "527eee0e", - "metadata": {}, - "outputs": [], - "source": [ - "ϵ_B[22:28]" - ] - }, - { - "cell_type": "markdown", - "id": "6f2f4475", - "metadata": {}, - "source": [ - "Weitere Iterationen verbessern das Ergebnis nicht mehr. Sie stabilisieren sich bei einem relativen Fehler von etwa 2.5 Maschinenepsilon:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3b2a8b77", - "metadata": {}, - "outputs": [], - "source": [ - "ϵ_B[end]/eps(Float64)" - ] - }, - { - "cell_type": "markdown", - "id": "6ff2d4b8", - "metadata": {}, - "source": [ - "Die Form Iteration A ist instabil. Bereits bei $i=16$ beginnt der relative Fehler wieder zu wachsen.\n", - "\n", - "Ursache ist eine typische Auslöschung. Die Seitenlängen $s_n$ werden sehr schnell klein. Damit ist\n", - "$a_n=\\sqrt{4-s_n^2}$ nur noch wenig kleiner als 2 und bei der Berechnung von $s_{2n}=\\sqrt{2-a_n}$ tritt ein typischer Auslöschungseffekt auf.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ca6c5ca2", - "metadata": {}, - "outputs": [], - "source": [ - "setprecision(80) # precision für BigFloat\n", - "\n", - "s = sqrt(BigFloat(2))\n", - "\n", - "@printf \" a = √(4-s^2) als BigFloat und als Float64\\n\\n\"\n", - "\n", - "for i = 3:44\n", - " s = iterationA(s)\n", - " x = sqrt(4-s^2)\n", - " if i > 20\n", - " @printf \"%i %30.26f %20.16f \\n\" i x Float64(x)\n", - " end \n", - "end\n" - ] - }, - { - "cell_type": "markdown", - "id": "5e4994b3", - "metadata": {}, - "source": [ - "Man sieht die Abnahme der Zahl der signifikanten Ziffern. Man sieht auch, dass eine Verwendung von `BigFloat` mit einer Mantissenlänge von hier 80 Bit das Einsetzen des Auslöschungseffekts nur etwas hinaussschieben kann. \n", - "\n", - "**Gegen instabile Algorithmen helfen in der Regel nur bessere, stabile Algorithmen und nicht genauere Maschinenzahlen!**\n", - "\n", - ":::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "Offensichtlich tritt bei der Berechnung von $2-a_n$ bereits relativ früh\n", - "eine Abnahme der Anzahl der signifikanten Ziffern (Auslöschung) auf, \n", - "bevor schließlich bei der Berechnung von $a_n=\\sqrt{4-s_n^2}$ \n", - "selbst schon Auslöschung zu einem unbrauchbaren Ergebnis führt.\n", - "\n", - ":::" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/Pi2.ipynb b/nb/Pi2.ipynb deleted file mode 100644 index 5f89df1..0000000 --- a/nb/Pi2.ipynb +++ /dev/null @@ -1,313 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "9e1ef849", - "metadata": {}, - "source": [ - "---\n", - "format:\n", - " html:\n", - " include-in-header:\n", - " text: |\n", - " \n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "beff12c8", - "metadata": {}, - "source": [ - "# Ein Beispiel zur Stabilität von Gleitkommaarithmetik\n", - "\n", - "## Berechnung von $\\pi$ nach Archimedes\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a7810264", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: false\n", - "#| echo: false\n", - "#| output: false\n", - "using PlotlyJS, Random\n", - "using HypertextLiteral\n", - "using JSON, UUIDs\n", - "using Base64\n", - "\n", - "\n", - "## see https://github.com/JuliaPlots/PlotlyJS.jl/blob/master/src/PlotlyJS.jl\n", - "## https://discourse.julialang.org/t/encode-a-plot-to-base64/27765/3\n", - "function IJulia.display_dict(p::PlotlyJS.SyncPlot)\n", - " Dict(\n", - " # \"application/vnd.plotly.v1+json\" => JSON.lower(p),\n", - " # \"text/plain\" => sprint(show, \"text/plain\", p),\n", - " \"text/html\" => let\n", - " buf = IOBuffer()\n", - " show(buf, MIME(\"text/html\"), p)\n", - " #close(buf)\n", - " #String(resize!(buf.data, buf.size))\n", - " String(take!(buf))\n", - " end,\n", - " \"image/png\" => let\n", - " buf = IOBuffer()\n", - " buf64 = Base64EncodePipe(buf)\n", - " show(buf64, MIME(\"image/png\"), p)\n", - " close(buf64)\n", - " #String(resize!(buf.data, buf.size))\n", - " String(take!(buf))\n", - " end,\n", - "\n", - " )\n", - " end\n", - "\n", - " function Base.show(io::IO, mimetype::MIME\"text/html\", p::PlotlyJS.SyncPlot)\n", - " uuid = string(UUIDs.uuid4())\n", - " show(io,mimetype,@htl(\"\"\"\n", - "
\n", - " \n", - "\"\"\"))\n", - "end " - ] - }, - { - "cell_type": "markdown", - "id": "8d4bd1ab", - "metadata": {}, - "source": [ - "Eine untere Schranke für $2\\pi$, den Umfang des Einheitskreises, erhält man durch die\n", - "Summe der Seitenlängen eines dem Einheitskreis eingeschriebenen regelmäßigen $n$-Ecks.\n", - " Die Abbildung links zeigt, wie man beginnend mit einem Viereck der Seitenlänge $s_4=\\sqrt{2}$ die Eckenzahl iterativ verdoppelt.\n", - "\n", - ":::{.narrow}\n", - "\n", - "| Abb. 1 | Abb.2 |\n", - "| :-: | :-: |\n", - "| ![](../images/pi1.png) | ![](../images/pi2.png) |\n", - ": {tbl-colwidths=\"[57,43]\"}\n", - "\n", - ":::\n", - "\n", - "\n", - "Die zweite Abbildung zeigt die Geometrie der Eckenverdoppelung.\n", - "\n", - "Mit\n", - "$|\\overline{AC}|= s_{n},\\quad |\\overline{AB}|= |\\overline{BC}|= s_{2n},\\quad |\\overline{MN}| =a, \\quad |\\overline{NB}| =1-a,$ liefert Pythagoras für die Dreiecke $MNA$ und\n", - " $NBA$ jeweils\n", - "$$\n", - " a^2 + \\left(\\frac{s_{n}}{2}\\right)^2 = 1\\qquad\\text{bzw.} \\qquad\n", - " (1-a)^2 + \\left(\\frac{s_{n}}{2}\\right)^2 = s_{2n}^2\n", - "$$\n", - "Elimination von $a$ liefert die Rekursion\n", - "$$\n", - " s_{2n} = \\sqrt{2-\\sqrt{4-s_n^2}} \\qquad\\text{mit Startwert}\\qquad\n", - " s_4=\\sqrt{2}\n", - "$$\n", - "für die Länge $s_n$ **einer** Seite des eingeschriebenen regelmäßigen\n", - "$n$-Ecks.\n", - "\n", - "\n", - "Die Folge $(n\\cdot s_n)$\n", - "konvergiert monoton von unten gegen den\n", - "Grenzwert $2\\pi$:\n", - "$$\n", - " n\\, s_n \\rightarrow 2\\pi % \\qquad\\text{und} \\qquad {n c_n}\\downarrow 2\\pi\n", - "$$\n", - "Der relative Fehler der Approximation von 2π durch ein $n$-Eck ist:\n", - "$$\n", - " \\epsilon_n = \\left| \\frac{n\\, s_n-2 \\pi}{2\\pi} \\right|\n", - "$$\n", - "\n", - "\n", - "## Zwei Iterationsvorschriften^[nach: Christoph Überhuber, „Computer-Numerik“ Bd. 1, Springer 1995, Kap. 2.3]\n", - "Die Gleichung\n", - "$$\n", - " s_{2n} = \\sqrt{2-\\sqrt{4-s_n^2}}\\qquad \\qquad \\textrm{(Iteration A)}\n", - "$$\n", - "ist mathematisch äquivalent zu\n", - "$$\n", - " s_{2n} = \\frac{s_n}{\\sqrt{2+\\sqrt{4-s_n^2}}} \\qquad \\qquad \\textrm{(Iteration B)}\n", - "$$\n", - "\n", - "(Bitte nachrechnen!) \n", - "\n", - "\n", - "\n", - "Allerdings ist Iteration A schlecht konditioniert und numerisch instabil, wie der folgende Code zeigt. Ausgegeben wird die jeweils berechnete Näherung für π.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3f238690", - "metadata": {}, - "outputs": [], - "source": [ - "using Printf\n", - "\n", - "iterationA(s) = sqrt(2 - sqrt(4 - s^2))\n", - "iterationB(s) = s / sqrt(2 + sqrt(4 - s^2))\n", - "\n", - "s_B = s_A = sqrt(2) # Startwert \n", - "\n", - "ϵ(x) = abs(x - 2π)/2π # rel. Fehler \n", - "\n", - "ϵ_A = Float64[] # Vektoren für den Plot\n", - "ϵ_B = Float64[]\n", - "is = Float64[]\n", - "\n", - "@printf \"\"\" approx. Wert von π\n", - " n-Eck Iteration A Iteration B\n", - "\"\"\"\n", - "\n", - "for i in 3:35\n", - " push!(is, i)\n", - " s_A = iterationA(s_A) \n", - " s_B = iterationB(s_B) \n", - " doublePi_A = 2^i * s_A\n", - " doublePi_B = 2^i * s_B\n", - " push!(ϵ_A, ϵ(doublePi_A))\n", - " push!(ϵ_B, ϵ(doublePi_B))\n", - " @printf \"%14i %20.15f %20.15f\\n\" 2^i doublePi_A/2 doublePi_B/2 \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "0c0178f5", - "metadata": {}, - "source": [ - "Während Iteration B sich stabilisiert bei einem innerhalb der Maschinengenauigkeit korrekten Wert für π, wird Iteration A schnell instabil. Ein Plot der relativen Fehler $\\epsilon_i$ bestätigt das:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f415aab0", - "metadata": {}, - "outputs": [], - "source": [ - "using PlotlyJS\n", - "\n", - "layout = Layout(xaxis_title=\"Iterationsschritte\", yaxis_title=\"rel. Fehler\",\n", - " yaxis_type=\"log\", yaxis_exponentformat=\"power\", \n", - " xaxis_tick0=2, xaxis_dtick=2)\n", - "\n", - "plot([scatter(x=is, y=ϵ_A, mode=\"markers+lines\", name=\"Iteration A\", yscale=:log10), \n", - " scatter(x=is, y=ϵ_B, mode=\"markers+lines\", name=\"Iteration B\", yscale=:log10)],\n", - " layout) \n" - ] - }, - { - "cell_type": "markdown", - "id": "02116ab2", - "metadata": {}, - "source": [ - "## Stabilität und Auslöschung\n", - "\n", - "Bei $i=26$ erreicht Iteration B einen relativen Fehler in der Größe des Maschinenepsilons:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3d50cba2", - "metadata": {}, - "outputs": [], - "source": [ - "ϵ_B[22:28]" - ] - }, - { - "cell_type": "markdown", - "id": "5ba088ba", - "metadata": {}, - "source": [ - "Weitere Iterationen verbessern das Ergebnis nicht mehr. Sie stabilisieren sich bei einem relativen Fehler von etwa 2.5 Maschinenepsilon:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2bcae61d", - "metadata": {}, - "outputs": [], - "source": [ - "ϵ_B[end]/eps(Float64)" - ] - }, - { - "cell_type": "markdown", - "id": "0bfd8235", - "metadata": {}, - "source": [ - "Die Form Iteration A ist instabil. Bereits bei $i=16$ beginnt der relative Fehler wieder zu wachsen.\n", - "\n", - "Ursache ist eine typische Auslöschung. Die Seitenlängen $s_n$ werden sehr schnell klein. Damit ist\n", - "$a_n=\\sqrt{4-s_n^2}$ nur noch wenig kleiner als 2 und bei der Berechnung von $s_{2n}=\\sqrt{2-a_n}$ tritt ein typischer Auslöschungseffekt auf.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "365d4c27", - "metadata": {}, - "outputs": [], - "source": [ - "setprecision(80) # precision für BigFloat\n", - "\n", - "s = sqrt(BigFloat(2))\n", - "\n", - "@printf \" a = √(4-s^2) als BigFloat und als Float64\\n\\n\"\n", - "\n", - "for i = 3:44\n", - " s = iterationA(s)\n", - " x = sqrt(4-s^2)\n", - " if i > 20\n", - " @printf \"%i %30.26f %20.16f \\n\" i x Float64(x)\n", - " end \n", - "end\n" - ] - }, - { - "cell_type": "markdown", - "id": "04736a02", - "metadata": {}, - "source": [ - "Man sieht die Abnahme der Zahl der signifikanten Ziffern. Man sieht auch, dass eine Verwendung von `BigFloat` mit einer Mantissenlänge von hier 80 Bit das Einsetzen des Auslöschungseffekts nur etwas hinaussschieben kann. \n", - "\n", - "**Gegen instabile Algorithmen helfen in der Regel nur bessere, stabile Algorithmen und nicht genauere Maschinenzahlen!**\n", - "\n", - ":::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "Offensichtlich tritt bei der Berechnung von $2-a_n$ bereits relativ früh\n", - "eine Abnahme der Anzahl der signifikanten Ziffern (Auslöschung) auf, \n", - "bevor schließlich bei der Berechnung von $a_n=\\sqrt{4-s_n^2}$ \n", - "selbst schon Auslöschung zu einem unbrauchbaren Ergebnis führt.\n", - "\n", - ":::" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/ablaufsteuerung.ipynb b/nb/ablaufsteuerung.ipynb deleted file mode 100644 index 10687ed..0000000 --- a/nb/ablaufsteuerung.ipynb +++ /dev/null @@ -1,83 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "cdcef88f", - "metadata": {}, - "source": [ - "# Verzweigungen\n", - "\n", - "::: {.column-margin}\n", - ":::\n", - "\n", - "### If\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "13854f8c", - "metadata": {}, - "outputs": [], - "source": [ - "x = 3\n", - "y = 66\n", - "\n", - "if x\n", - "2. als Editor/IDE **Visual Studio Code** installieren: \n", - "3. im VS Code Editor die **Julia language extension** installieren: \n", - "\n", - "Einstieg:\n", - "\n", - "- In VS Code eine neue Datei mit der Endung `.jl` anlegen\n", - "- Julia-Code schreiben\n", - "- {{< kbd Shift-Enter >}} oder {{< kbd Ctrl-Enter >}} am Ende einer Anweisung oder eines Blocks startet ein Julia-REPL, Code wird ins REPL kopiert und ausgeführt \n", - "- [Tastenbelegungen für VS Code](https://code.visualstudio.com/docs/getstarted/keybindings#_keyboard-shortcuts-reference)\n", - "und [Julia in VS Code](https://www.julia-vscode.org/docs/stable/userguide/keybindings/)\n", - "\n", - "\n", - "\n", - "## Arbeiten auf dem [Jupyterhub-Webserver](https://misun103.mathematik.uni-leipzig.de/)\n", - "\n", - "### Jupyterhub & Jupyter\n", - "\n", - "- [Jupyterhub](https://de.wikipedia.org/wiki/Project_Jupyter) ist ein Multi-User-Server für Jupyter.\n", - "- Jupyter ist eine web-basierte interaktive Programmierumgebung, die\n", - "- ursprünglich in und für Python geschrieben, inzwischen eine\n", - " Vielzahl von Programmiersprachen nutzen kann.\n", - "- In Jupyter bearbeitet man sogenannte *notebooks*. Das sind strukturiere Textdateien (JSON), erkennbar an der Dateiendung \n", - " `*.ipynb`.\n", - "\n", - "Unser Jupyterhub-Server: \n", - "\n", - "Nach dem Einloggen in Jupyterhub erscheint ein Dateimanager:\n", - "\n", - "![Jupyterhub Dateimanager](../images/notebook001.png)\n", - "\n", - "Mit diesem kann man:\n", - "\n", - "- vorhandene *notebooks* öffnen,\n", - "- neue *notebooks* anlegen,\n", - "- Dateien, z.B. *notebooks*, vom lokalen Rechner hochladen,\n", - "- die Sitzung mit `Logout` beenden (bitte nicht vergessen!). \n", - "\n", - "### Jupyter notebooks\n", - "\n", - "![Jupyter Notebook](../images/notebook003.png)\n", - "\n", - "\n", - "*Notebooks* bestehen aus Zellen. Zellen können \n", - "\n", - "- Code oder \n", - "- Text/Dokumentation (Markdown) \n", - "\n", - "enthalten. In Textzellen können mit die Auszeichnungssprache [Markdown](https://de.wikipedia.org/wiki/Markdown) zur Formatierung und LaTeX für mathematische Gleichungen verwendet werden. \n", - "\n", - "Es sei empfohlen, die Punkte `User Interface Tour` und `Keyboard Shortcuts` im `Help`-Menü anzuschauen. Die Zelle, die man gerade bearbeitet, kann im `command mode` oder `edit mode` sein. \n", - "\n", - "\n", - "\n", - "```{html}\n", - "\n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - " \n", - "
Einige Kommandos
command modeedit mode
Mode aktivierenESC
\n", - "```\n", - "\n", - "\n", - "\n", - "| | *command mode* | *edit mode* |\n", - "|:-------|:---------------:|:-----------:|\n", - "| Mode aktivieren | `ESC` | Doppelklick oder `Enter` in Zelle |\n", - "| neue Zelle | `b` | `Alt-Enter` |\n", - "| Zelle löschen | `dd` | |\n", - "| Notebook speichern | `s` | `Ctrl-s` |\n", - "\n", - "\n", - "\n", - "- Notebook speichern:\n", - "\n", - " - `Ctrl-s` in Edit Mode\n", - " - `s` in Command mode\n", - " - `Menu -> File -> Save & Checkpoint`\n", - " - `Menu -> File -> Rename`: Umbenennen (falls es noch\n", - " \\\"Untitled1\\\" heißt) `
`{=html}`
`{=html}\n", - "\n", - "- Notebook schließen:\n", - "\n", - " - `Menu -> File -> Close & Halt` `
`{=html}`
`{=html}\n", - "\n", - "- Ausführen von Julia:\n", - "\n", - " - `Ctrl-Enter`: Run cell\n", - " - `Shift-Enter`: Run cell, move to next cell\n", - " - `Alt-Enter`: run cell, insert new cell below\n", - "\n", - "\n", - "\n", - "bla backslash\n", - "\n", - "![](../images/notebook002.png)\n", - "\n", - "bla backslash\n", - "\n", - "\n", - "------------------------------------------------------------------------\n", - "\n", - "Wenn eine Zelle \\\"arbeitet\\\", wird ihre Zellen-Nummer zu einem `*` und\n", - "die `kernel busy`-Anzeige (Voller schwarzer Punkt oben rechts neben der\n", - "Julia-Version) erscheint. Falls das zu lange dauert (ein *infinite loop*\n", - "ist schnell programmiert), dann\n", - "\n", - "- `Menu -> Kernel -> Interrupt` anklicken; falls das wirkungslos ist,\n", - "- `Menu -> Kernel -> Restart` anklicken.\n", - "\n", - "Danach müssen alle Zellen, die weiterhin benötigte Definitionen,\n", - "`using`-Anweisungen etc enthalten, wieder ausgeführt werden!\n", - "\n", - "------------------------------------------------------------------------\n", - "\n", - "**Am Ende der Arbeit bitte immer:**\n", - "\n", - "- `Menu -> File -> Save & Checkpoint`\n", - "- `Menu -> File -> Close & Halt`\n", - "- `Logout`\n", - ":::\n", - "\n", - "::: {#73820119 .cell .markdown}\n", - "#### Markdown-Zellen\n", - "\n", - "neben den üblichen Markdown-Elementen können auch diese auch\n", - "`HTML`-Anweisungen und Mathematische Formeln in LaTeX-Form enthalten.\n", - "LaTeX-Formeln werden in `$...$` oder `$$...$$` (Display-Form)\n", - "eingeschlossen.\n", - ":::\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/example.ipynb b/nb/example.ipynb deleted file mode 100644 index 81caba6..0000000 --- a/nb/example.ipynb +++ /dev/null @@ -1,146 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "1847e5bc", - "metadata": {}, - "source": [ - "# Some Julia Code\n", - "\n", - "\n", - "1. ?forvarianrte\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fd1a489b", - "metadata": {}, - "outputs": [], - "source": [ - "?for" - ] - }, - { - "cell_type": "markdown", - "id": "62aee612", - "metadata": {}, - "source": [ - "## Einfache rechnerei\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "23afd224", - "metadata": {}, - "outputs": [], - "source": [ - "2^33+33" - ] - }, - { - "cell_type": "markdown", - "id": "d1f050b2", - "metadata": {}, - "source": [ - "## colored console graphs produced by `Benchmarktools.jl`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a9b6a7c8", - "metadata": {}, - "outputs": [], - "source": [ - "using BenchmarkTools\n", - "\n", - "@benchmark sum(rand(1000))" - ] - }, - { - "cell_type": "markdown", - "id": "948d948e", - "metadata": {}, - "source": [ - "## structure of floating point numbers\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fbe94ce0", - "metadata": {}, - "outputs": [], - "source": [ - "function printbitsf64(x::Float64)\n", - " s = bitstring(x)\n", - " printstyled(s[1], color = :blue, reverse=true)\n", - " printstyled(s[2:12], color = :green, reverse=true)\n", - " printstyled(s[13:end], color=:red, bold=true, reverse=true)\n", - " print(\"\\n\")\n", - "end\n", - "\n", - "printbitsf64(27.56640625)" - ] - }, - { - "cell_type": "markdown", - "id": "611f43fa", - "metadata": {}, - "source": [ - "### illustrate machine epsilon...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "294f9e7e", - "metadata": {}, - "outputs": [], - "source": [ - "Eps=0.5\n", - "while 1 != 1 + Eps\n", - " Eps /= 2\n", - " printbitsf64(1+Eps)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "34e578b1", - "metadata": {}, - "source": [ - "### ... some ugly colors\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9771dbc3", - "metadata": {}, - "outputs": [], - "source": [ - "function printbits2f64(x::Float64)\n", - " s = bitstring(x)\n", - " printstyled(s[1], color = 142, reverse=true)\n", - " printstyled(s[2:12], color = 190, reverse=false, underline=true)\n", - " printstyled(s[13:end], color= 27, bold=true, reverse=true)\n", - " print(\"\\n\")\n", - "end\n", - "\n", - "printbits2f64(27.56640625)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/first_contact.ipynb b/nb/first_contact.ipynb deleted file mode 100644 index 10d6885..0000000 --- a/nb/first_contact.ipynb +++ /dev/null @@ -1,628 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "65cc0031", - "metadata": {}, - "source": [ - "# First Contact\n", - "\n", - "Dieses Kapitel soll beim 'Loslegen' helfen. Es läßt viele Details weg und die Codebeispiele sind oft eher suboptimal. \n", - "\n", - "\n", - "## Julia als Taschenrechner\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9151e6d", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: true\n", - "#| echo: false\n", - "#| output: false\n", - "\n", - "using REPL, Markdown\n", - "\n", - "function mhelp(s,n,m)\n", - " helptxt = Core.eval(Main, REPL.helpmode(s))\n", - " helpstr=Markdown.plaininline(helptxt)\n", - " print(\"...\\n\", join(split(helpstr,'\\n')[n:m],'\\n'), \"\\n...\")\n", - "end;\n", - "\n", - "function Tab(s)\n", - " l = filter(x->startswith(x,s), REPL.doc_completions(s))\n", - " println.(l[2:end])\n", - " return # return nothing, since broadcast println produces empty vector\n", - "end\n", - "\n", - "▷ = |>\n", - "\n", - "# IJulia.set_verbose(true)" - ] - }, - { - "cell_type": "markdown", - "id": "3c611742", - "metadata": {}, - "source": [ - "Berechne $\\qquad 12^{1/3} + \\frac{3\\sqrt{2}}{\\sin(0.5)-\\cos(\\frac{\\pi}{4})\\log(3)}+ e^5$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fd02456e", - "metadata": {}, - "outputs": [], - "source": [ - "12^(1/3) + 3sqrt(2) / (sin(.5) - cos(pi/4)*log(3)) + exp(5)" - ] - }, - { - "cell_type": "markdown", - "id": "9ce12c0f", - "metadata": {}, - "source": [ - "Man beachte:\n", - "\n", - "- Potenzen schreibt man `a^b`.\n", - "- Die Konstante `pi` ist vordefiniert.\n", - "- `log()` ist der natürliche Logarithmus.\n", - "- Das Multiplikationszeichen `a*b` kann nach einer Zahl weggelassen werden, wenn eine Variable, Funktion oder Klammer folgt.\n", - "\n", - "\n", - "## Die wichtigsten Tasten: `Tab` und `?` {#sec-tab}\n", - "\n", - "Man drücke beim Programmieren immer wieder die Tabulatortaste, sobald 2...3 Buchstaben eines Wortes getippt sind. Es werden dann mögliche Ergänzungen angezeigt bzw. ergänzt, wenn die Ergänzung eindeutig ist. Das spart Zeit und bildet ungemein:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e2ca6f27", - "metadata": {}, - "outputs": [], - "source": [ - "lo = \"lo\" #| hide_line\n", - "lo ▷ Tab" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9fdfabe6", - "metadata": {}, - "outputs": [], - "source": [ - "pri = \"pri\" #| hide_line\n", - "pri ▷ Tab" - ] - }, - { - "cell_type": "markdown", - "id": "d8ecd73b", - "metadata": {}, - "source": [ - "Die eingebaute Julia-Hilfe `?name` zu allen Funktionen und Konstrukten ist sehr umfassend. Hier ein eher kurzes Beispiel: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9ba34e9d", - "metadata": {}, - "outputs": [], - "source": [ - "?for" - ] - }, - { - "cell_type": "markdown", - "id": "c798d174", - "metadata": {}, - "source": [ - ":::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "::: {.cell }\n", - "``` {.julia .cell-code}\n", - "?for\n", - "```\n", - "\n", - "::: {.cell-output .cell-output-stdout}\n", - "```\n", - "search: for foreach foldr floor mapfoldr factorial EOFError OverflowError\n", - "\n", - "for loops repeatedly evaluate a block of statements while iterating over a sequence of values.\n", - "\n", - "Examples\n", - "\n", - "julia> for i in [1, 4, 0]\n", - " println(i)\n", - " end\n", - "1\n", - "4\n", - "0\n", - "\n", - "```\n", - ":::\n", - ":::\n", - ":::\n", - "\n", - "\n", - "## Variablen und Zuweisungen\n", - "\n", - "Variablen entstehen durch Zuweisung *(assignment)* mit dem Zuweisungsoperator `=` . Danach können sie in weiteren Anweisungen verwendet werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2f60e4e5", - "metadata": {}, - "outputs": [], - "source": [ - "x = 1 + sqrt(5) \n", - "y = x / 2" - ] - }, - { - "cell_type": "markdown", - "id": "20819c0a", - "metadata": {}, - "source": [ - "Im interaktiven Betrieb zeigt Julia das Ergebnis der letzten Operation an.\n", - "\n", - ":::{.callout-note .titlenormal}\n", - "Zuweisungen sind keine mathematischen Gleichungen. Die Semantik des Zuweisungsoperators (Gleichheitszeichens) ist: \n", - "\n", - "- berechne die rechte Seite und\n", - "- weise das Ergebnis der linken Seite zu.\n", - "\n", - "Ausdrücke wie `x + y = sin(2)` sind daher unzulässig. Links darf nur ein Variablenname stehen.\n", - ":::\n", - "\n", - "\n", - "## Datentypen\n", - "\n", - "Julia ist eine [stark typisierte](https://de.wikipedia.org/wiki/Starke_Typisierung) Sprache. Alle Objekte haben einen Typ. \n", - "So gibt es unter anderem die Basistypen \n", - "\n", - "- Ganze Zahlen *(integers)*,\n", - "- Gleitkommazahlen *(floating point numbers)*,\n", - "- Zeichenketten *(strings)* und \n", - "- Wahrheitswerte *(booleans)*.\n", - "\n", - "Den Typ einer Variablen kann man mit der Funktion `typeof()` ermitteln. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2874204c", - "metadata": {}, - "outputs": [], - "source": [ - "#| warning: true\n", - "#| error: true\n", - "for x ∈ (42, 12.0, 3.3e4, \"Hallo!\", true)\n", - " println(\"x = \", x, \" ..... Typ: \", typeof(x))\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "d5343251", - "metadata": {}, - "source": [ - "Die Standard-Gleitkommazahl hat eine Länge von 64 Bit, entspricht also einer `double` in C/C++/Java.\n", - "\n", - "Julia ist eine [dynamisch typisierte](https://de.wikipedia.org/wiki/Dynamische_Typisierung) Sprache. \n", - "Variablen haben keinen Typ. Sie sind typlose Referenzen (Zeiger) auf Objekte. \n", - "Wenn man vom „Typ einer Variablen“ spricht, meint man den Typ des Objektes, das der Variablen gerade zugewiesen ist. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "544f8fe6", - "metadata": {}, - "outputs": [], - "source": [ - "x = sqrt(2)\n", - "\n", - "println( typeof(x), \" - Wert von x = $x\" )\n", - "\n", - "x = \"Jetzt bin ich keine Gleitkommazahl mehr!\"\n", - "\n", - "println( typeof(x), \" - Wert von x = $x\" )" - ] - }, - { - "cell_type": "markdown", - "id": "b1734df1", - "metadata": {}, - "source": [ - "## Druckanweisungen\n", - "Die Funktion `println()` unterscheidet sich von `print()` dadurch, dass sie am Ende einen Zeilenvorschub ausgibt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b44d0f53", - "metadata": {}, - "outputs": [], - "source": [ - "print(y)\n", - "print(\"...die Zeile geht weiter...\")\n", - "print(\"immernoch...\")\n", - "println(y)\n", - "println(\"Neue Zeile\")\n", - "println(\"Neue Zeile\")" - ] - }, - { - "cell_type": "markdown", - "id": "3baa2a89", - "metadata": {}, - "source": [ - "Beide Funkionen können als Argument eine Liste von *strings* und Variablen bekommen. Man kann Variablen auch in *strings* einbetten, indem man dem Variablennamen ein Dollarzeichen voranstellt *(string interpolation)*.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fa3b2601", - "metadata": {}, - "outputs": [], - "source": [ - "x = 23\n", - "y = 3x + 5\n", - "zz = \"Fertig!\"\n", - "println(\"x= \", x, \" ...und y= \", y, \"...\", zz) # 1. Variante\n", - "println(\"x= $x ...und y= $y...$zz\") # Variante mit string interpolation" - ] - }, - { - "cell_type": "markdown", - "id": "fe3b44d2", - "metadata": {}, - "source": [ - ":::{.callout-note .titlenormal collapse=true icon=false }\n", - "## Wenn man ein Dollarzeichen drucken will...\n", - "\n", - "muss man einen *backslash* voranstellen. Wenn man einen *backslash* drucken will, muss man ihn verdoppeln.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "198c1231", - "metadata": {}, - "outputs": [], - "source": [ - "println(\"Ein Dollar: 1\\$ und drei backslashs: \\\\\\\\\\\\ \")" - ] - }, - { - "cell_type": "markdown", - "id": "847182e6", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "## Funktionen\n", - "Funktionsdefinitionen beginnen mit dem Schlüsselwort `function` und enden mit dem Schlüsselwort `end`. In der Regel haben sie eine oder mehrere Argumente und geben beim Aufruf ein berechnetes Objekt mit der `return`-Anweisung zurück.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8c4c8af3", - "metadata": {}, - "outputs": [], - "source": [ - "function hypotenuse(a, b) # heute besonders umständlich\n", - " c2 = a^2 + b^2\n", - " c = sqrt(c2)\n", - " return c \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "270a968d", - "metadata": {}, - "source": [ - "Nach ihrer Definition kann die Funktion benutzt (aufgerufen) werden. Die in der Definition verwendeten Variablen `a,b,c,c2` sind lokale Variablen und stehen außerhalb der Funktionsdefinition nicht zur Verfügung. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "aeb1b763", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: true\n", - "x = 3\n", - "z = hypotenuse(x, 4)\n", - "println(\"z = $z\")\n", - "println(\"c = $c\")" - ] - }, - { - "cell_type": "markdown", - "id": "83623a5d", - "metadata": {}, - "source": [ - "Sehr einfache Funktionen können auch als Einzeiler definiert werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bb93d920", - "metadata": {}, - "outputs": [], - "source": [ - "hypotenuse(a, b) = sqrt(a^2+b^2)" - ] - }, - { - "cell_type": "markdown", - "id": "28cfec18", - "metadata": {}, - "source": [ - "## Tests\n", - "Tests liefern einen Wahrheitswert zurück. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a778d1c9", - "metadata": {}, - "outputs": [], - "source": [ - "x = 3^2\n", - "x < 2^3" - ] - }, - { - "cell_type": "markdown", - "id": "43717a30", - "metadata": {}, - "source": [ - "Neben den üblichen arithmetischen Vergleichen `==, !=, <, <= ,> ,>=` \n", - "gibt es noch viele andere Tests. Natürlich kann man das Ergebnis eines Tests auch einer Variablen zuweisen, welche dann vom Typ `Bool` ist. Die logischen Operatoren `&&`, `||` und Negation `!` können in Tests verwendet werden. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b425b2bf", - "metadata": {}, - "outputs": [], - "source": [ - "test1 = \"Auto\" in [\"Fahrrad\", \"Auto\", \"Bahn\"]\n", - "test2 = x == 100 || !(x <= 30 && x > 8)\n", - "test3 = startswith(\"Lampenschirm\", \"Lamp\") \n", - "println(\"$test1 $test2 $test3\")" - ] - }, - { - "cell_type": "markdown", - "id": "b8b63af7", - "metadata": {}, - "source": [ - "## Verzweigungen\n", - "Verzweigungen (bedingte Anweisungen) haben die Form \n", - "\n", - "```default\n", - "if \n", - " \n", - " \n", - " ...\n", - "end\n", - "``` \n", - "\n", - "\n", - "Ein `else`-Zweig und `elseif`-Zweige sind möglich.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "759c7b60", - "metadata": {}, - "outputs": [], - "source": [ - "x = sqrt(100)\n", - "\n", - "if x > 20\n", - " println(\"Seltsam!\")\n", - "else\n", - " println(\"OK\")\n", - " y = x + 3\n", - "end " - ] - }, - { - "cell_type": "markdown", - "id": "92f05a99", - "metadata": {}, - "source": [ - "Einrückungen verbessern die Lesbarkeit, sind aber fakultativ. Zeilenumbrüche trennen Anweisungen. Das ist auch durch Semikolon möglich. Obiger Codeblock ist für Julia identisch zu folgender Zeile:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "75c38c3c", - "metadata": {}, - "outputs": [], - "source": [ - "# Bitte nicht so programmieren! Sie werden es bereuen!\n", - "x=sqrt(100); if x > 20 println(\"Seltsam!\") else println(\"OK\"); y = x + 3 end " - ] - }, - { - "cell_type": "markdown", - "id": "6c916fa7", - "metadata": {}, - "source": [ - "Es wird dringend empfohlen, von Anfang an den eigenen Code übersichtlich mit sauberen Einrückungen zu formatieren!\n", - "\n", - "\n", - "## Einfache `for`-Schleifen\n", - "\n", - "zum wiederholten Abarbeiten von Anweisungen haben die Form\n", - "```default\n", - "for = Start:Ende\n", - " \n", - " \n", - " ...\n", - "end\n", - "```\n", - "Beispiel:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8f6ff3c3", - "metadata": {}, - "outputs": [], - "source": [ - "sum = 0\n", - "for i = 1:100\n", - " sum = sum + i\n", - "end \n", - "sum" - ] - }, - { - "cell_type": "markdown", - "id": "6ba98544", - "metadata": {}, - "source": [ - "## Arrays\n", - "1-dimensionale Arrays (Vektoren) sind eine einfache Form von Containern. Man kann sie mit echigen Klammern anlegen\n", - "und auf die Elemente per Index zugreifen. Die Indizierung beginnt mit 1. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bde3f18d", - "metadata": {}, - "outputs": [], - "source": [ - "v = [12, 33.2, 17, 19, 22]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ab7ae1b1", - "metadata": {}, - "outputs": [], - "source": [ - "typeof(v)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cd6f6101", - "metadata": {}, - "outputs": [], - "source": [ - "v[1] = v[4] + 10\n", - "v" - ] - }, - { - "cell_type": "markdown", - "id": "4cd8e309", - "metadata": {}, - "source": [ - "Man kann leere Vektoren anlegen und sie verlängern.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4e643897", - "metadata": {}, - "outputs": [], - "source": [ - "v = [] # leerer Vektor\n", - "push!(v, 42)\n", - "push!(v, 13)\n", - "v" - ] - }, - { - "cell_type": "markdown", - "id": "d3e2209e", - "metadata": {}, - "source": [ - ":::{.callout-note icon=\"false\" .titlenormal collapse=\"true\" font-variant-ligatures=\"no-contextual\" }\n", - "\n", - "## Nachtrag: wie die Wirkung der Tab-Taste auf dieser Seite simuliert wurde...\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8bb956d4", - "metadata": {}, - "outputs": [], - "source": [ - "using REPL\n", - "\n", - "function Tab(s)\n", - " l = filter(x->startswith(x,s), REPL.doc_completions(s))\n", - " println.(l[2:end])\n", - " return # return nothing, since broadcast println produces empty vector\n", - "end\n", - "\n", - "▷ = |> # https://docs.julialang.org/en/v1/manual/functions/#Function-composition-and-piping\n", - "\n", - "pri = \"pri\";" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a417e43d", - "metadata": {}, - "outputs": [], - "source": [ - "pri ▷ Tab" - ] - }, - { - "cell_type": "markdown", - "id": "71efa254", - "metadata": {}, - "source": [ - ":::" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/first_contact.nbconvert.ipynb b/nb/first_contact.nbconvert.ipynb deleted file mode 100644 index 865f4a1..0000000 --- a/nb/first_contact.nbconvert.ipynb +++ /dev/null @@ -1,493 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "cd3f6abe", - "metadata": {}, - "source": [ - "# First Contact\n", - "\n", - "Dieses Kapitel enthält einige \"pädagogische Halbwahrheiten\", d.h., es vereinfacht und lässt Details weg.\n", - "\n", - "## Julia als Taschenrechner\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0dbe789e", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:34.132000Z", - "iopub.status.busy": "2023-03-08T16:05:33.746000Z", - "iopub.status.idle": "2023-03-08T16:05:37.286000Z", - "shell.execute_reply": "2023-03-08T16:05:37.175000Z" - } - }, - "outputs": [], - "source": [ - "#| eval: true\n", - "#| echo: false\n", - "#| output: false\n", - "IJulia.set_verbose(true)" - ] - }, - { - "cell_type": "markdown", - "id": "a2b52996", - "metadata": {}, - "source": [ - "Berechne $\\qquad 12^{1/3} + \\frac{3\\sqrt{2}}{\\sin(0.5)-\\cos(\\frac{\\pi}{4})\\log(3)}+ e^5$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c831420f", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:37.336000Z", - "iopub.status.busy": "2023-03-08T16:05:37.335000Z", - "iopub.status.idle": "2023-03-08T16:05:37.620000Z", - "shell.execute_reply": "2023-03-08T16:05:37.618000Z" - } - }, - "outputs": [], - "source": [ - "12^(1/3) + 3sqrt(2) / (sin(.5) - cos(pi/4)*log(3)) + exp(5)" - ] - }, - { - "cell_type": "markdown", - "id": "a9f3359b", - "metadata": {}, - "source": [ - "Man beachte:\n", - "\n", - "- Potenzen schreibt man `a^b`.\n", - "- Die Konstante `pi` ist vordefiniert.\n", - "- `log()` ist der natürliche Logarithmus.\n", - "- Das Multiplikationszeichen `a*b` kann nach einer Zahl weggelassen werden, wenn eine Variable, Funktion oder Klammer folgt.\n", - "\n", - "\n", - "## Variablen und Zuweisungen\n", - "\n", - "Variablen entstehen durch Zuweisung *(assignment)*. Durch Zuweisung definierte Variablen können danach in weiteren Anweisungen verwendet werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5ff20c70", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:37.625000Z", - "iopub.status.busy": "2023-03-08T16:05:37.624000Z", - "iopub.status.idle": "2023-03-08T16:05:37.657000Z", - "shell.execute_reply": "2023-03-08T16:05:37.655000Z" - } - }, - "outputs": [], - "source": [ - "x = 1 + sqrt(5) \n", - "y = x / 2" - ] - }, - { - "cell_type": "markdown", - "id": "e7db7bb5", - "metadata": {}, - "source": [ - ":::{.indentb}\n", - "Zuweisungen sind keine mathematischen Gleichungen. Die Semantik des Zuweisungsoperators (d.h., des Gleichheitszeichens) ist: \n", - "\n", - "- berechne die rechte Seite und\n", - "- weise das Ergebnis der linken Seite zu.\n", - "\n", - "Ausdrücke wie `x + y = sin(2)` sind daher unzulässig, links darf nur ein Variablenname stehen.\n", - ":::\n", - "\n", - "\n", - "## Datentypen\n", - "\n", - "Julia ist eine [stark typisierte](https://de.wikipedia.org/wiki/Starke_Typisierung) Sprache. Alle Objekte haben einen Typ. \n", - "So gibt es unter anderem die Basistypen \n", - "\n", - "- Ganze Zahlen *(integers)*,\n", - "- Gleitkommazahlen *(floating point numbers)*,\n", - "- Zeichenketten *(strings)* und \n", - "- Wahrheitswerte *(booleans)*.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ae3af394", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:37.662000Z", - "iopub.status.busy": "2023-03-08T16:05:37.661000Z", - "iopub.status.idle": "2023-03-08T16:05:38.219000Z", - "shell.execute_reply": "2023-03-08T16:05:38.217000Z" - } - }, - "outputs": [], - "source": [ - "#| warning: true\n", - "#| error: true\n", - "for x ∈ (42, 12.0, 3.3e4, \"Hallo!\", true)\n", - " println(\"x = \", x, \" ..... Typ: \", typeof(x))\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "213bef1c", - "metadata": {}, - "source": [ - "Die Standard-Gleitkommazahl hat eine Länge von 64 Bit, entspricht also einer `double` in C/C++/Java.\n", - "\n", - "Julia ist eine [dynamisch typisierte](https://de.wikipedia.org/wiki/Dynamische_Typisierung) Sprache. \n", - "Variablen haben keinen Typ. Sie sind typlose Referenzen (Zeiger) auf Objekte. \n", - "Wenn man vom „Typ einer Variablen“ spricht, meint man den Typ des Objektes, das der Variablen gerade zugewiesen ist. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2d6c0d1b", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.225000Z", - "iopub.status.busy": "2023-03-08T16:05:38.223000Z", - "iopub.status.idle": "2023-03-08T16:05:38.316000Z", - "shell.execute_reply": "2023-03-08T16:05:38.315000Z" - } - }, - "outputs": [], - "source": [ - "x = sqrt(2)\n", - "println( typeof(x) )\n", - "x = \"Jetzt bin ich keine Gleitkommazahl mehr!\"\n", - "println( typeof(x) )" - ] - }, - { - "cell_type": "markdown", - "id": "f2329446", - "metadata": {}, - "source": [ - "## Druckanweisungen\n", - "Die Funktion `println()` unterscheidet sich von `print()` dadurch, dass sie am Ende einen Zeilenvorschub ausgibt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d4a7260d", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.321000Z", - "iopub.status.busy": "2023-03-08T16:05:38.320000Z", - "iopub.status.idle": "2023-03-08T16:05:38.369000Z", - "shell.execute_reply": "2023-03-08T16:05:38.367000Z" - } - }, - "outputs": [], - "source": [ - "print(y)\n", - "print(\"...die Zeile geht weiter...\")\n", - "print(\"immernoch...\")\n", - "println(y)\n", - "println(\"Neue Zeile\")\n", - "println(\"Neue Zeile\")" - ] - }, - { - "cell_type": "markdown", - "id": "dccc9577", - "metadata": {}, - "source": [ - "Beide Funkionen können als Argument eine Liste von *strings* und Variablen bekommen. Man kann Variablen auch in *strings* einbetten, indem man dem Variablennamen ein Dollarzeichen voranstellt *(string interpolation)*.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7a2116bd", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.374000Z", - "iopub.status.busy": "2023-03-08T16:05:38.373000Z", - "iopub.status.idle": "2023-03-08T16:05:38.402000Z", - "shell.execute_reply": "2023-03-08T16:05:38.400000Z" - } - }, - "outputs": [], - "source": [ - "x = 23\n", - "y = 3x + 5\n", - "zz = \"Fertig!\"\n", - "println(\"x= \", x, \" ...und y= \", y, \"...\", zz) # 1. Variante\n", - "println(\"x= $x ...und y= $y...$zz\") # Variante mit string interpolation" - ] - }, - { - "cell_type": "markdown", - "id": "ae5eaf6f", - "metadata": {}, - "source": [ - ":::{.indentb}\n", - "Wenn man ein Dollarzeichen drucken will, muss man einen *backslash* voranstellen. Wenn man einen *backslash* drucken will, muss man ihn verdoppeln.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f7d26a60", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.407000Z", - "iopub.status.busy": "2023-03-08T16:05:38.406000Z", - "iopub.status.idle": "2023-03-08T16:05:38.434000Z", - "shell.execute_reply": "2023-03-08T16:05:38.432000Z" - } - }, - "outputs": [], - "source": [ - "println(\"Ein Dollar: 1\\$ und drei backslashs: \\\\\\\\\\\\ \")" - ] - }, - { - "cell_type": "markdown", - "id": "f40cee12", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "## Funktionen\n", - "Funktionsdefinitionen beginnen mit dem Schlüsselwort `function` und enden mit dem Schlüsselwort `end`. In der Regel haben sie eine oder mehrere Argumente und geben beim Aufruf ein berechnetes Objekt mit der `return`-Anweisung zurück.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b6574086", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.439000Z", - "iopub.status.busy": "2023-03-08T16:05:38.438000Z", - "iopub.status.idle": "2023-03-08T16:05:38.633000Z", - "shell.execute_reply": "2023-03-08T16:05:38.631000Z" - } - }, - "outputs": [], - "source": [ - "function hypotenuse(a, b)\n", - " c2 = a^2 + b^2\n", - " c = sqrt(c2)\n", - " return c \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "d70272a0", - "metadata": {}, - "source": [ - "Nach ihrer Definition kann die Funktion benutzt (aufgerufen) werden. Die in der Definition verwendeten Variablen `a,b,c,c2` sind lokale Variablen und stehen außerhalb der Funktionsdefinition nicht zur Verfügung. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5df842f6", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:38.638000Z", - "iopub.status.busy": "2023-03-08T16:05:38.636000Z", - "iopub.status.idle": "2023-03-08T16:05:39.346000Z", - "shell.execute_reply": "2023-03-08T16:05:39.344000Z" - } - }, - "outputs": [], - "source": [ - "#| error: true\n", - "x = 3\n", - "z = hypotenuse(x, 4)\n", - "println(z)\n", - "println(c)" - ] - }, - { - "cell_type": "markdown", - "id": "dc012140", - "metadata": {}, - "source": [ - "Sehr einfache Funktionen können auch kürzer als Einzeiler definiert werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6aec78b0", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:39.351000Z", - "iopub.status.busy": "2023-03-08T16:05:39.350000Z", - "iopub.status.idle": "2023-03-08T16:05:39.381000Z", - "shell.execute_reply": "2023-03-08T16:05:39.379000Z" - } - }, - "outputs": [], - "source": [ - "hypotenuse(a, b) = sqrt(a^2+b^2)" - ] - }, - { - "cell_type": "markdown", - "id": "d57bc14f", - "metadata": {}, - "source": [ - "## Tests\n", - "Tests liefern einen Wahrheitswert zurück. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0e42d502", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:39.387000Z", - "iopub.status.busy": "2023-03-08T16:05:39.386000Z", - "iopub.status.idle": "2023-03-08T16:05:39.420000Z", - "shell.execute_reply": "2023-03-08T16:05:39.418000Z" - } - }, - "outputs": [], - "source": [ - "x = 2^8\n", - "x < 3" - ] - }, - { - "cell_type": "markdown", - "id": "814e4e5c", - "metadata": {}, - "source": [ - "Neben den üblichen arithmetischen Vergleichen `==, !=, <, <= ,> ,>=` \n", - "gibt es noch viele andere Tests. Natürlich kann man das Ergebnis eines Tests auch einer Variablen zuweisen, welche dann vom Typ `Bool` ist. Die logischen Operatoren `&&`, `||` und Negation `!` können in Tests verwendet werden. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3899c1c9", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:39.425000Z", - "iopub.status.busy": "2023-03-08T16:05:39.424000Z", - "iopub.status.idle": "2023-03-08T16:05:39.479000Z", - "shell.execute_reply": "2023-03-08T16:05:39.477000Z" - } - }, - "outputs": [], - "source": [ - "test1 = \"Auto\" in [\"Fahrrad\", \"Auto\", \"Bahn\"]\n", - "test2 = x == 100 || x in [1,2,4,7]\n", - "test3 = startswith(\"Lampenschirm\", \"Lamp\") \n", - "println(\"$test1 $test2 $test3\")" - ] - }, - { - "cell_type": "markdown", - "id": "067897ae", - "metadata": {}, - "source": [ - "## Verzweigungen\n", - "Verzweigungen (bedingte Anweisungen) haben die Form `if end`. Ein `else`-Zweig ist möglich.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "34db87a5", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:39.484000Z", - "iopub.status.busy": "2023-03-08T16:05:39.483000Z", - "iopub.status.idle": "2023-03-08T16:05:39.518000Z", - "shell.execute_reply": "2023-03-08T16:05:39.516000Z" - } - }, - "outputs": [], - "source": [ - "x = sqrt(100)\n", - "\n", - "if x > 20\n", - " println(\"Seltsam!\")\n", - "else\n", - " println(\"OK\")\n", - " y = x + 3\n", - "end " - ] - }, - { - "cell_type": "markdown", - "id": "2c0677f6", - "metadata": {}, - "source": [ - "Einrückungen und Zeilenumbrüche verbessern die Lesbarkeit, sind aber fakultativ. Anweisungen können auch durch Semikolon getrennt werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3b169201", - "metadata": { - "execution": { - "iopub.execute_input": "2023-03-08T16:05:39.523000Z", - "iopub.status.busy": "2023-03-08T16:05:39.521000Z", - "iopub.status.idle": "2023-03-08T16:05:39.554000Z", - "shell.execute_reply": "2023-03-08T16:05:39.552000Z" - } - }, - "outputs": [], - "source": [ - "if x > 20 println(\"Seltsam!\") else println(\"OK\"); y = x + 3 end " - ] - }, - { - "cell_type": "markdown", - "id": "f225e8eb", - "metadata": {}, - "source": [ - "## Einfache Schleifen\n", - "\n", - "\n", - "\n", - "## Arrays\n", - "1-dimensionale Arrays (Vektoren) sind eine einfache Form von Containern. Man kann sie mit echigen Klammern anlegen\n", - "\n", - "\n", - "und auf die Elemente per Index zugreifen. Die Indizierung beginnt mit 1. \n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - }, - "language_info": { - "file_extension": ".jl", - "mimetype": "application/julia", - "name": "julia", - "version": "1.8.5" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/intro.ipynb b/nb/intro.ipynb deleted file mode 100644 index 1da6084..0000000 --- a/nb/intro.ipynb +++ /dev/null @@ -1,114 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "10c7d783", - "metadata": {}, - "source": [ - "---\n", - "title: Introduction\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "f2e8fc05", - "metadata": {}, - "source": [ - "## Noch eine Programmiersprache?\n", - "\n", - "Die Ziele der Schöpfer von Julia kann man in [Why we created Julia](https://julialang.org/blog/2012/02/why-we-created-julia/) nachlesen. Kurzfassung:\n", - "\n", - "“We want a language that is\n", - "\n", - "open source\n", - "with the speed of C\n", - "obvious, familiar mathematical notation like Matlab\n", - "as usable for general programming as Python\n", - "as easy for statistics as R\n", - "as natural for string processing as Perl\n", - "as powerful for linear algebra as Matlab\n", - "as good at gluing programs together as the shell\n", - "dirt simple to learn, yet keeps the most serious hackers happy”\n", - "\n", - "\n", - "\"Wir wollen eine Sprache, die\n", - "\n", - "- *open source* ist \n", - "- die Geschwindigkeit von C hat \n", - "- obvious, familiar mathematical notation like Matlab\n", - "- as usable for general programming as Python\n", - "- as easy for statistics as R\n", - "- as natural for string processing as Perl\n", - "- as powerful for linear algebra as Matlab\n", - "- as good at gluing programs together as the shell\n", - "- dirt simple to learn, yet keeps the most serious hackers happy\"\n", - "\n", - "vs code: erzeuge eine Datei mit der Endung `.jl`, starte ein REPL mit dem Kommando \n", - "Alt-Enter am Ende einer Zeile oder Anweisung f\"uhrt dazu, dass die Anweisung \n", - "is REPL kopiert und ausgefuehrt wird\n", - "\n", - "alt-enter execute in julia Repl\n", - "shift-enter: ex. and move to next line\n", - "\n", - "die Erstinstallation von Paketen kann sehr lange dauern. \n", - "\n", - "im Jupyterhub sind die im Kurs nenötigten Pakete vorinstalliert. \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "## colored console graphs produced by `Benchmarktools.jl`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "62fcada8", - "metadata": {}, - "outputs": [], - "source": [ - "using BenchmarkTools\n", - "\n", - "@benchmark sum(rand(1000))" - ] - }, - { - "cell_type": "markdown", - "id": "00dc9599", - "metadata": {}, - "source": [ - "## structure of floating point numbers\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ccc6afab", - "metadata": {}, - "outputs": [], - "source": [ - "function printbitsf64(x::Float64)\n", - " s = bitstring(x)\n", - " printstyled(s[1], color = :blue, reverse=true)\n", - " printstyled(s[2:12], color = :green, reverse=true)\n", - " printstyled(s[13:end], color=:red, bold=true, reverse=true)\n", - " print(\"\\n\")\n", - "end\n", - "\n", - "printbitsf64(27.56640625)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/makie.ipynb b/nb/makie.ipynb deleted file mode 100644 index 229ff81..0000000 --- a/nb/makie.ipynb +++ /dev/null @@ -1,77 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "7d6e8e63", - "metadata": {}, - "source": [ - "---\n", - "title: makie\n", - "---" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fff03da7", - "metadata": {}, - "outputs": [], - "source": [ - "using CairoMakie\n", - "\n", - "\n", - "f = Figure()\n", - "Axis(f[1, 1])\n", - "\n", - "xs = 1:0.2:10\n", - "ys_low = -0.2 .* sin.(xs) .- 0.25\n", - "ys_high = 0.2 .* sin.(xs) .+ 0.25\n", - "\n", - "band!(xs, ys_low, ys_high)\n", - "band!(xs, ys_low .- 1, ys_high .-1, color = :red)\n", - "\n", - "f" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "242380da", - "metadata": {}, - "outputs": [], - "source": [ - "f = Figure()\n", - "Axis(f[1, 1])\n", - "\n", - "xs = LinRange(0, 10, 100)\n", - "ys = LinRange(0, 15, 100)\n", - "zs = [cos(x) * sin(y) for x in xs, y in ys]\n", - "\n", - "contour!(zs,levels=-1:0.1:1)\n", - "\n", - "f" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ff5c9a2d", - "metadata": {}, - "outputs": [], - "source": [ - "fig, ax, hm = heatmap(randn(20, 20))\n", - "Colorbar(fig[1, 2], hm)\n", - "fig" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/numerictypes.ipynb b/nb/numerictypes.ipynb deleted file mode 100644 index 9fd8218..0000000 --- a/nb/numerictypes.ipynb +++ /dev/null @@ -1,1296 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "24a532a6", - "metadata": {}, - "source": [ - "# Maschinenzahlen\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d7654522", - "metadata": {}, - "outputs": [], - "source": [ - "for x ∈ ( 3, 3.3e4, Int16(20), Float32(3.3e4), UInt16(9) )\n", - " @show x sizeof(x) typeof(x)\n", - " println()\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "0a0f532c", - "metadata": {}, - "source": [ - "## Ganze Zahlen *(integers)*\n", - "\n", - "Ganze Zahlen werden grundsätzlich als Bitmuster fester Länge gespeichert. Damit ist der Wertebereich endlich. \n", - "**Innerhalb dieses Wertebereichs** sind Addition, Subtraktion, Multiplikation und die Ganzzahldivision mit Rest \n", - "exakte Operationen ohne Rundungsfehler. \n", - "\n", - "Ganze Zahlen gibt es in den zwei Sorten `Signed` (mit Vorzeichen) und `Unsigned`, die man als Maschinenmodelle für ℤ bzw. ℕ auffassen kann.\n", - "\n", - "\n", - "### *Unsigned integers*\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9d1aa3b9", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "1668b3fb", - "metadata": {}, - "source": [ - "UInts sind Binärzahlen mit n=8, 16, 32, 64 oder 128 Bits Länge und einem entsprechenden Wertebereich von\n", - "$$\n", - "0 \\le x < 2^n \n", - "$$\n", - "Sie werden im *scientific computing* eher selten verwendet. Bei hardwarenaher Programmierung dienen sie z.B. dem Umgang mit Binärdaten und Speicheradressen. Deshalb werden sie von Julia standardmäßig auch als Hexadezimalzahlen (mit Präfix `0x` und Ziffern `0-9a-f`) dargestellt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7e8f2435", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e472b90c", - "metadata": {}, - "source": [ - "### *Signed Integers* \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8f1272d6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "eab3eaca", - "metadata": {}, - "source": [ - "*Integers* haben den Wertebereich\n", - "$$\n", - "-2^{n-1} \\le x < 2^{n-1} \n", - "$$\n", - "\n", - "\n", - "In Julia sind ganze Zahlen standardmäßig 64 Bit groß:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "af6239db", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "04f5044e", - "metadata": {}, - "source": [ - "Sie haben daher den Wertebereich: \n", - "$$\n", - "-9.223.372.036.854.775.808 \\le x \\le 9.223.372.036.854.775.807\n", - "$$\n", - "\n", - "32-Bit-Integers haben den Wertebereich \n", - "$$\n", - "-2.147.483.648 \\le x \\le 2.147.483.647\n", - "$$\n", - "Der Maximalwert $2^{31}-1$ is zufällig gerade eine Mersenne-Primzahl:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3f219052", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "fde7b29b", - "metadata": {}, - "source": [ - "Negative Zahlen werden im Zweierkomplement dargestellt:\n", - "\n", - "$x \\Rightarrow -x$ entspricht: _flip all bits, then add 1_\n", - "\n", - "Das sieht so aus:\n", - "\n", - "::: {.content-visible when-format=\"html\"}\n", - "![Eine Darstellung des fiktiven Datentyps `Int4`](../images/Int4.png){width=50%}\n", - ":::\n", - "\n", - "::: {.content-visible when-format=\"pdf\"}\n", - "![Eine Darstellung des fiktiven Datentyps `Int4`](../images/Int4.png){width=50%}\n", - ":::\n", - "\n", - "Das höchstwertige Bit zeigt das Vorzeichen an. Sein „Umkippen“ entspricht allerdings nicht der Operation `x → -x`.\n", - "\n", - ":::{.callout-important}\n", - "Die gesamte Ganzzahlarithmetik ist eine __Arithmetik modulo $2^n$__\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7578aa32", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d0ef29dd", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e78ca374", - "metadata": {}, - "source": [ - "Keine Fehlermeldung, keine Warnung! Ganzzahlen fester Länge liegen nicht auf einer Geraden, sondern auf einem Kreis!\n", - "\n", - ":::\n", - "\n", - "Schauen wir uns ein paar *Integers* an:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4ee2d6c8", - "metadata": {}, - "outputs": [], - "source": [ - "using Printf\n", - "\n", - "for i in (1, 2, 7, -7, 2^50, -1, Int16(7), Int8(7))\n", - " s = bitstring(i)\n", - " t = typeof(i)\n", - " @printf \"%20i %-5s ⇒ %s\\n\" i t s \n", - "end " - ] - }, - { - "cell_type": "markdown", - "id": "b8640e2b", - "metadata": {}, - "source": [ - "Julia hat Funktionen, die über die Datentypen informieren (*introspection*):\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1ac371fb", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2dcf1ad6", - "metadata": {}, - "outputs": [], - "source": [ - "typemin(UInt64), typemax(UInt64), BigInt(typemax(UInt64))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e56ba2ac", - "metadata": {}, - "outputs": [], - "source": [ - "typemin(Int8), typemax(Int8)" - ] - }, - { - "cell_type": "markdown", - "id": "8d38072e", - "metadata": {}, - "source": [ - "## Arithmetik ganzer Zahlen\n", - "\n", - "#### Addition, Multiplikation\n", - "Die Operationen `+`,`-`,`*` haben die übliche exakte Arithmetik **modulo $2^{64}$**.\n", - "\n", - "#### Potenzen `a^b`\n", - "\n", - "- Potenzen `a^n` werden für natürliche Exponenten `n` ebenfalls modulo $2^{64}$ exakt berechnet. \n", - "- Für negative Exponenten ist das Ergebnis eine Gleitkommazahl.\n", - "- `0^0` ist [selbstverständlich](https://en.wikipedia.org/wiki/Zero_to_the_power_of_zero#cite_note-T4n3B-4) gleich 1.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e10e1e7b", - "metadata": {}, - "outputs": [], - "source": [ - "(-2)^63, 2^64, 3^(-3), 0^0 " - ] - }, - { - "cell_type": "markdown", - "id": "9f170e32", - "metadata": {}, - "source": [ - "- Für natürliche Exponenten wird [*exponentiation by squaring*](https://de.wikipedia.org/wiki/Bin%C3%A4re_Exponentiation) verwendet, so dass z.B. `x^23` nur 7 Multiplikationen benötigt: \n", - "$$\n", - "x^{23} = \\left( \\left( (x^2)^2 \\cdot x \\right)^2 \\cdot x \\right)^2 \\cdot x \n", - "$$\n", - "\n", - "#### Division\n", - "\n", - "- Division `/` erzeugt eine Gleitkommazahl.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ce734b5f", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "bc0af941", - "metadata": {}, - "source": [ - "#### Ganzzahldivision und Rest\n", - "\n", - "- Die Funktionen `div(a,b)`, `rem(a,b)` und `divrem(a,b)` berechnen den Quotient der Ganzzahldivision, den dazugehörigen Rest *(remainder)* bzw. beides als Tupel. \n", - "- Für `div(a,b)` gibt es die Operatorform `a ÷ b` (Eingabe: `\\div`) und für `rem(a,b)` die Operatorform `a % b`. \n", - "- Standardmäßig wird bei der Division „zur Null hin gerundet“, wodurch der dazugehörige Rest dasselbe Vorzeichen wie der Dividend `a` trägt: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8e496544", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "2efcbcdb", - "metadata": {}, - "source": [ - "- Eine von `RoundToZero` abweichende Rundungsregel kann bei den Funktionen als optionales 3. Argument angegeben werden. \n", - "- `?RoundingMode` zeigt die möglichen Rundungsregeln an. \n", - "- Für die Rundungsregel `RoundDown` („in Richtung minus unendlich\"), wodurch der dazugehörige Rest dasselbe Vorzeichen wie der Divisor `b` bekommt, gibt es auch die Funktionen `fld(a,b)` *(floored division)* und `mod(a,b)`:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1a64561b", - "metadata": {}, - "outputs": [], - "source": [ - "@show divrem(-27, 4, RoundDown)\n", - "@show (fld(-27, 4), mod(-27, 4))\n", - "@show (fld( 27, -4), mod( 27, -4));" - ] - }, - { - "cell_type": "markdown", - "id": "f4c504dc", - "metadata": {}, - "source": [ - "Für alle Rundungsregeln gilt:\n", - "```\n", - "div(a, b, RoundingMode) * b + rem(a, b, RoundingMode) = a\n", - "```\n", - "\n", - "#### Der Datentyp `BigInt`\n", - "\n", - "Der Datentyp `BigInt` ermöglicht Ganzzahlen beliebiger Länge. Der benötigte Speicher wird dynamisch allokiert.\n", - "\n", - "Numerische Konstanten haben automatisch einen ausreichend großen Typ:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6e5e2595", - "metadata": {}, - "outputs": [], - "source": [ - "z = 10\n", - "@show typeof(z)\n", - "z = 10_000_000_000_000_000 # 10 Billiarden\n", - "@show typeof(z)\n", - "z = 10_000_000_000_000_000_000 # 10 Trillionen\n", - "@show typeof(z)\n", - "z = 10_000_000_000_000_000_000_000_000_000_000_000_000_000 # 10 Sextilliarden\n", - "@show typeof(z);" - ] - }, - { - "cell_type": "markdown", - "id": "c959faa9", - "metadata": {}, - "source": [ - "Meist wird man allerdings den Datentyp `BigInt` explizit anfordern müssen, damit nicht modulo $2^{64}$ gerechnet wird:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1118bb76", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "0075815b", - "metadata": {}, - "source": [ - "*Arbitrary precision arithmetic* kostet einiges an Speicherplatz und Rechenzeit.\n", - "\n", - "Wir vergleichen den Zeit- und Speicherbedarf bei der Aufsummation von 10 Millionen Ganzzahlen als `Int64` und als `BigInt`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5306bf40", - "metadata": {}, - "outputs": [], - "source": [ - "# 10^7 Zufallszahlen, gleichverteilt zwischen -10^7 und 10^7 \n", - "vec_int = rand(-10^7:10^7, 10^7)\n", - "\n", - "# Dieselben Zahlen als BigInts\n", - "vec_bigint = BigInt.(vec_int)" - ] - }, - { - "cell_type": "markdown", - "id": "2d052b71", - "metadata": {}, - "source": [ - "Einen ersten Eindruck vom Zeit- und Speicherbedarf gibt das `@time`-Macro:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "18de4e6a", - "metadata": {}, - "outputs": [], - "source": [ - "@time x = sum(vec_int)\n", - "@show x typeof(x)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dc805fe6", - "metadata": {}, - "outputs": [], - "source": [ - "@time x = sum(vec_bigint)\n", - "@show x typeof(x);" - ] - }, - { - "cell_type": "markdown", - "id": "0506b2d0", - "metadata": {}, - "source": [ - "Durch die Just-in-Time-Compilation von Julia ist die einmalige Ausführung einer Funktion wenig aussagekräftig. Das Paket `BenchmarkTools` stellt u.a. das Macro `@benchmark` bereit, das eine Funktion mehrfach aufruft und die Ausführungszeiten als Histogramm darstellt.\n", - "\n", - ":::{.ansitight}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8235276b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ee87e4ab", - "metadata": {}, - "outputs": [], - "source": [ - "@benchmark sum($vec_bigint)" - ] - }, - { - "cell_type": "markdown", - "id": "a3e7ba45", - "metadata": {}, - "source": [ - ":::\n", - "Die `BigInt`-Addition ist mehr als 30 mal langsamer. \n", - "\n", - "\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "id": "4a985f0b", - "metadata": {}, - "source": [ - "\n", - "## Gleitkommazahlen\n", - "\n", - "Aus _floating point numbers_ kann man im Deutschen **[Gleit|Fließ]--[Komma|Punkt]--Zahlen** machen \n", - "und tatsächlich kommen alle 4 Varianten in der Literatur vor. \n", - "\n", - "In der Numerischen Mathematik spricht man auch gerne von **Maschinenzahlen**.\n", - "\n", - "\n", - "### Grundidee \n", - "\n", - "- Eine „feste Anzahl von Vor- und Nachkommastellen“ ist für viele Probleme ungeeignet.\n", - "- Eine Trennung zwischen „gültigen Ziffern“ und Größenordnung (Mantisse und Exponent) wie in der wissenschaftlichen Notation ist wesentlich flexibler.\n", - " $$ 345.2467 \\times 10^3\\qquad 34.52467\\times 10^4\\qquad \\underline{3.452467\\times 10^5}\\qquad 0.3452467\\times 10^6\\qquad 0.03452467\\times 10^7$$ \n", - "- Zur Eindeutigkeit muss man eine dieser Formen auswählen. In der mathematischen Analyse von Maschinenzahlen wählt man oft die Form, bei der die erste Nachkommastelle ungleich Null ist. Damit gilt für die Mantisse $m$: \n", - "$$\n", - "1 < m \\le (0.1)_b = b^{-1},\n", - "$$ \n", - "wobei $b$ die gewählte Basis des Zahlensystems bezeichnet.\n", - "- Wir wählen im Folgenden die Form, die der tatsächlichen Implementation auf dem Computer entspricht und legen fest: \n", - "Die Darstellung mit genau einer Ziffer ungleich Null vor dem Komma ist die __Normalisierte Darstellung__. Damit gilt \n", - "$$\n", - " b< m \\le 1.\n", - "$$ \n", - "- Bei Binärzahlen `1.01101`: ist diese Ziffer immer gleich Eins und man kann auf das Abspeichern dieser Ziffer verzichten. Diese tatsächlich abgespeicherte (gekürzte) Mantisse bezeichnen wir mit $M$, so dass \n", - "$$m = 1 + M$$ \n", - "gilt. \n", - "\n", - "\n", - ":::{.callout-note }\n", - " \n", - "## Maschinenzahlen\n", - "\n", - "Die Menge der Maschinenzahlen $𝕄(b, m, e_{min}, e_{max})$ ist charakterisiert durch die verwendete Basis $b$, die Mantissenlänge $m$ und den Wertebereich des Exponenten $\\{e_{min}, ... ,e_{max}\\}$. \n", - "\n", - "In unserer Konvention hat die Mantisse einer normalisierten Maschinenzahl eine Ziffer (der Basis $b$) ungleich Null vor dem Komma und $m-1$ Nachkommastellen. \n", - "\n", - "Wenn $b=2$ ist, braucht man daher nur $m-1$ Bits zur Speicherung der Mantisse normalisierter Gleitkommazahlen. \n", - "\n", - "Der Standard IEEE 754, der von der Mahrzahl der modernen Prozessoren und Programmiersprachen implementiert wird, definiert \n", - "\n", - "- `Float32` als $𝕄(2, 24, -126, 127 )$ und \n", - "- `Float64` als $𝕄(2, 53, -1022, 1023 ).$\n", - "\n", - ":::\n", - "\n", - "### Aufbau von `Float64` nach [Standard IEEE 754](https://de.wikipedia.org/wiki/IEEE_754)\n", - "\n", - "\n", - "::: {.content-visible when-format=\"html\"}\n", - "![Aufbau einer `Float64` (Quelle:^[Quelle: Codekaizen, CC BY-SA 4.0, via Wikimedia Commons ])\n", - "](../images/1024px-IEEE_754_Double_Floating_Point_Format.png)\n", - ":::\n", - "\n", - "::: {.content-visible when-format=\"pdf\"}\n", - "![Aufbau einer `Float64` \\mysmall{(Quelle: \\href{https://commons.wikimedia.org/wiki/File:IEEE_754_Double_Floating_Point_Format.svg}{Codekaizen}, \\href{https://creativecommons.org/licenses/by-sa/4.0}{CC BY-SA 4.0}, via Wikimedia Commons)}\n", - "](../images/1024px-IEEE_754_Double_Floating_Point_Format.png){width=\"70%\"}\n", - ":::\n", - "\n", - "\n", - "- 1 Vorzeichenbit $S$\n", - "- 11 Bits für den Exponenten, also $0\\le E \\le 2047$\n", - "- die Werte $E=0$ und $E=(11111111111)_2=2047$ sind reserviert für die Codierung von Spezialwerten wie\n", - "$\\pm0, \\pm\\infty$, NaN _(Not a Number)_ und denormalisierte Zahlen.\n", - "- 52 Bits für die (gekürzte) Mantisse $M,\\quad 0\\le M<1$, das entspricht etwa 16 Dezimalstellen\n", - "- Damit wird folgende Zahl dargestellt:\n", - "$$ x=(-1)^S \\cdot(1+M)\\cdot 2^{E-1023}$$\n", - "\n", - "Ein Beispiel:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b353480a", - "metadata": {}, - "outputs": [], - "source": [ - "x = 27.56640625\n" - ] - }, - { - "cell_type": "markdown", - "id": "14878920", - "metadata": {}, - "source": [ - "Das geht auch schöner:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0417cf2a", - "metadata": {}, - "outputs": [], - "source": [ - "function printbitsf64(x::Float64)\n", - " s = bitstring(x)\n", - " printstyled(s[1], color = :blue, reverse=true)\n", - " printstyled(s[2:12], color = :green, reverse=true)\n", - " printstyled(s[13:end], color=:red, bold=true, reverse=true)\n", - " print(\"\\n\")\n", - "end\n", - "\n", - "printbitsf64(x)" - ] - }, - { - "cell_type": "markdown", - "id": "f7e57f81", - "metadata": {}, - "source": [ - "und wir können S (in blau),E (grün) und M (rot) ablesen:\n", - "$$\n", - "\\begin{aligned}\n", - "S &= 0\\\\\n", - "E &= (10000000011)_2 = 2^{10} + 2^1 + 2^0 = 1027\\\\\n", - "M &= (.1011100100001)_2 = \\frac{1}{2} + \\frac{1}{2^3} + \\frac{1}{2^4} + \\frac{1}{2^5} + \\frac{1}{2^8} + \\frac{1}{2^{12}}\\\\\n", - "x &=(-1)^S \\cdot(1+M)\\cdot 2^{E-1023}\n", - "\\end{aligned}\n", - "$$\n", - "\n", - "\n", - "... und damit die Zahl rekonstruieren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1e357fb6", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "d9982c45", - "metadata": {}, - "source": [ - "- Die Maschinenzahlen 𝕄 bilden eine endliche, diskrete Untermenge von ℝ. Es gibt eine kleinste und eine größte Maschinenzahl und abgesehen davon haben alle x∈𝕄 einen Vorgänger und Nachfolger in 𝕄.\n", - "- Was ist der Nachfolger von x in 𝕄? Dazu setzen wir das kleinste Mantissenbit von 0 auf 1. \n", - "- Die Umwandlung eines Strings aus Nullen und Einsen in die entsprechende Maschinenzahl ist z.B. so möglich:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "749a668f", - "metadata": {}, - "outputs": [], - "source": [ - "ux = parse(UInt64, \"0100000000111011100100010000000000000000000000000000000000000001\", base=2)\n", - "reinterpret(Float64, ux)" - ] - }, - { - "cell_type": "markdown", - "id": "60852e8d", - "metadata": {}, - "source": [ - "Das kann man in Julia allerdings auch einfacher haben:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "df856949", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "915240b8", - "metadata": {}, - "source": [ - "Der Vorgänger von x ist:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "7844705c", - "metadata": {}, - "outputs": [], - "source": [ - "z = prevfloat(x)\n", - "println(z)\n", - "printbitsf64(z)" - ] - }, - { - "cell_type": "markdown", - "id": "4e9dcdfe", - "metadata": {}, - "source": [ - "## Maschinenepsilon\n", - "\n", - "- Den Abstand zwischen `1` und dem Nachfolger `nextfloat(1)` nennt man [**Maschinenepsilon**](https://en.wikipedia.org/wiki/Machine_epsilon). \n", - "- Für `Float64` mit einer Mantissenlänge von 52 Bit ist $\\epsilon=2^{-52}$.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "54f77992", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "efc48d58", - "metadata": {}, - "source": [ - "- Das Maschinenepsilon ist ein Maß für den relativen Abstand zwischen den Maschinenzahlen und quantifiziert die Aussage: „64-Bit-Gleitkommazahlen haben eine Genauigkeit von etwa 16 Dezimalstellen.“\n", - "- Das Maschinenepsilon ist etwas völlig anderes als die kleinste von Null verschiedene Gleitkommazahl:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bcbd1bcf", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "93097822", - "metadata": {}, - "source": [ - "- Ein Teil der Literatur verwendet eine andere Definition des Maschinenepsilons, die halb so groß ist. \n", - "$$\n", - "\\epsilon' = \\frac{\\epsilon}{2}\\approx 1.1\\times 10^{-16}\n", - "$$ \n", - "ist der maximale relative Fehler, der beim Runden einer reellen Zahl auf die nächste Maschinenzahl entstehen kann.\n", - "- Da Zahlen aus dem Intervall $(1-\\epsilon',1+\\epsilon']$ auf die Maschinenzahl $1$ gerundet werden, kann man $\\epsilon'$ auch definieren als: *die größte Zahl, für die in der Maschinenzahlarithmetik noch gilt: $1+\\epsilon' = 1$.* \n", - "\n", - "Auf diese Weise kann man das Maschinenepsilon auch berechnen:\n", - "\n", - ":::{.ansitight}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5c96f36c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "9c2d355d", - "metadata": {}, - "source": [ - "oder als Bitmuster:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0897f63f", - "metadata": {}, - "outputs": [], - "source": [ - "Eps=1\n", - "while 1 != 1 + Eps\n", - " Eps/= 2\n", - " printbitsf64(1+Eps)\n", - "end\n", - "Eps" - ] - }, - { - "cell_type": "markdown", - "id": "5a2a1ae0", - "metadata": {}, - "source": [ - ":::\n", - "\n", - ":::{.callout-note}\n", - "## Die Menge der (normalisierten) Maschinenzahlen\n", - "\n", - "- Im Intervall $[1,2)$ liegen $2^{52}$ äquidistante Maschinenzahlen.\n", - "- Danach erhöht sich der Exponent um 1 und die Mantisse $M$ wird auf 0 zurückgesetzt. Damit enthält das Intervall $[2,4)$ wiederum $2^{52}$ äquidistante Maschinenzahlen, ebenso das Intervall $[4,8)$ bis hin zu $[2^{1023}, 2^{1024})$. \n", - "- Ebenso liegen in den Intervallen $\\ [\\frac{1}{2},1), \\ [\\frac{1}{4},\\frac{1}{2}),...$ je $2^{52}$ äquidistante Maschinenzahlen, bis hinunter zu $[2^{-1022}, 2^{-1021})$. \n", - "- Dies bildet die Menge $𝕄_+$ der positiven Maschinenzahlen und es ist\n", - "$$\n", - "𝕄 = -𝕄_+ \\cup \\{0\\} \\cup 𝕄_+\n", - "$$\n", - "\n", - ":::\n", - "\n", - "Die größte und die kleinste positive normalisiert darstellbare Gleitkommazahl eines Gleitkommatyps kann man abfragen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3c0a75bb", - "metadata": {}, - "outputs": [], - "source": [ - "@show floatmax(Float64)\n", - "printbitsf64(floatmax(Float64))\n", - "\n", - "@show floatmin(Float64)\n", - "printbitsf64(floatmin(Float64))" - ] - }, - { - "cell_type": "markdown", - "id": "8bde2bbb", - "metadata": {}, - "source": [ - "## Runden auf Maschinenzahlen\n", - "\n", - "- Die Abbildung rd: ℝ $\\rightarrow$ 𝕄 soll zur nächstgelegenen darstellbaren Zahl runden. \n", - "- Standardrundungsregel: _round to nearest, ties to even_ \n", - " Wenn man genau die Mitte zwischen zwei Maschinenzahlen trifft *(tie)*, wählt man die, deren letztes Mantissenbit 0 ist. \n", - "- Begründung: damit wird statistisch in 50% der Fälle auf- und in 50% der Fälle abgerundet und so ein „statistischer Drift“ bei längeren Rechnungen vermieden. \n", - "- Es gilt:\n", - "$$\n", - "\\frac{|x-\\text{rd}(x)|}{|x|} \\le \\frac{1}{2} \\epsilon\n", - "$$\n", - "\n", - "\n", - "## Maschinenzahlarithmetik\n", - "\n", - "Die Maschinenzahlen sind als Untermenge von ℝ nicht algebraisch abgeschlossen. Schon die Summe zweier Maschinenzahlen wird in der Regel keine Maschinenzahl sein. \n", - "\n", - ":::{.callout-important}\n", - "Der Standard IEEE 754 fordert, dass die Maschinenzahlarithmetik das *gerundete exakte Ergebnis* liefert:\n", - "\n", - "Das Resultat muss gleich demjenigen sein, das bei einer exakten Ausführung der entsprechenden Operation mit anschließender Rundung entsteht.\n", - "$$\n", - " a \\oplus b = \\text{rd}(a + b)\n", - "$$ \n", - "Analoges muss für die Implemetierung der Standardfunktionen wie \n", - "wie `sqrt()`, `log()`, `sin()` ... gelten: Sie liefern ebenfalls die Maschinenzahl, die dem exakten Ergebnis am nächsten kommt.\n", - ":::\n", - "\n", - "\n", - "Die Arithmetik ist *nicht assoziativ*:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "24f9a783", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c04afc52", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "0db90e88", - "metadata": {}, - "source": [ - "Im ersten Fall (ohne Klammern) wird von links nach rechts ausgewertet:\n", - "$$\n", - "\\begin{aligned}\n", - "1 \\oplus 10^{-16} \\oplus 10^{-16} &=\n", - " (1 \\oplus 10^{-16}) \\oplus 10^{-16} \\\\ &= \n", - "\\text{rd}\\left(\\text{rd}(1 + 10^{-16}) + 10^{-16} \\right)\\\\\n", - "&= \\text{rd}(1 + 10^{-16})\\\\\n", - "&= 1\n", - "\\end{aligned}\n", - "$$\n", - "\n", - "Im zweiten Fall erhält man:\n", - "$$\n", - "\\begin{aligned}\n", - "1 \\oplus \\left(10^{-16} \\oplus 10^{-16}\\right) &=\n", - "\\text{rd}\\left(1 + \\text{rd}(10^{-16} + 10^{-16}) \\right)\\\\\n", - "&= \\text{rd}(1 + 2*10^{-16})\\\\\n", - "&= 1.0000000000000002\n", - "\\end{aligned}\n", - "$$\n", - "\n", - "\n", - "Es sei auch daran erinnert, dass sich selbst „einfache“ Dezimalbrüche häufig nicht exakt als Maschinenzahlen darstellen lassen:\n", - "\n", - "$$\n", - "\\begin{aligned}\n", - "(0.1)_{10} &= (0.000110011001100110011001100...)_2 = (0.000\\overline{1100})_2 \\\\\n", - " (0.3)_{10} &= (0.0100110011001100110011001100..)_2 = (0.0\\overline{1001})_2 \n", - " \\end{aligned}\n", - " $$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "221ec38c", - "metadata": {}, - "outputs": [], - "source": [ - "printbitsf64(0.1)\n", - "printbitsf64(0.3)" - ] - }, - { - "cell_type": "markdown", - "id": "727318a8", - "metadata": {}, - "source": [ - "Folge:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "37770ed0", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8502b772", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6b8f708e", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "2fa26d1a", - "metadata": {}, - "source": [ - "Bei der Ausgabe einer Maschinenzahl muss der Binärbruch in einen Dezimalbruch entwickelt werden. Man kann sich auch mehr Stellen dieser Dezimalbruchentwicklung anzeigen lassen: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4163149b", - "metadata": {}, - "outputs": [], - "source": [ - "using Printf\n", - "@printf(\"%.30f\", 0.1)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "66a1cbdc", - "metadata": {}, - "outputs": [], - "source": [ - "@printf(\"%.30f\", 0.3)" - ] - }, - { - "cell_type": "markdown", - "id": "de6afd2b", - "metadata": {}, - "source": [ - "Die Binärbruch-Mantisse einer Maschinenzahl kann eine lange oder sogar unendlich-periodische Dezimalbruchentwicklung haben. Dadurch \n", - "sollte man sich nicht eine „höheren Genauigkeit“ suggerieren lassen! \n", - "\n", - ":::{.callout-important}\n", - "Moral: wenn man `Float`s auf Gleichheit testen will, sollte man fast immer eine dem Problem angemessene realistische Genauigkeit `epsilon` festlegen und \n", - "darauf testen:\n", - "\n", - "```julia\n", - "epsilon = 1.e-10\n", - "\n", - "if abs(x-y) < epsilon\n", - " # ...\n", - "end\n", - "```\n", - ":::\n", - "\n", - "## Normalisierte und Denormalisierte Maschinenzahlen\n", - "\n", - "Die Lücke zwischen Null und der kleinsten normalisierten Maschinenzahl $2^{-1022} \\approx 2.22\\times 10^{-308}$ \n", - "ist mit denormalisierten Maschinenzahlen besiedelt. \n", - "\n", - "Zum Verständnis nehmen wir ein einfaches Modell: \n", - "\n", - "- Sei 𝕄(10,4,±5) die Menge der Maschinenzahlen zur Basis 10 mit 4 Mantissenstellen (eine vor dem Komma, 3 Nachkommastellen) und dem Exponentenbereich -5 ≤ E ≤ 5.\n", - "- Dann ist die normalisierte Darstellung (Vorkommastelle ungleich 0)\n", - " von z.B. 1234.0 gleich 1.234e3 und von 0.00789 gleich 7.890e-3.\n", - "- Es ist wichtig, dass die Maschinenzahlen bei jedem Rechenschritt normalisiert gehalten werden. Nur so wird die Mantissenlänge voll ausgenutzt und die Genauigkeit ist maximal.\n", - "- Die kleinste positive normalisierte Zahl in unserem Modell ist `x = 1.000e-5`. Schon `x/2` müsste auf 0 gerundet werden. \n", - "- Hier erweist es sich für viele Anwendungen als günstiger, auch denormalisierte *(subnormal)* Zahlen zuzulassen und `x/2` als `0.500e-5` oder `x/20` als `0.050e-5` darzustellen. \n", - "- Dieser *gradual underflow* ist natürlich mit einem Verlust an gültigen Stellen und damit Genauigkeit verbunden.\n", - "\n", - "\n", - "Im `Float`-Datentyp werden solche *subnormal values* dargestellt durch ein Exponentenfeld, in dem alle Bits gleich Null sind:\n" - ] - }, - { - "cell_type": "markdown", - "id": "13e1fcdb", - "metadata": {}, - "source": [ - ":::{.ansitight}\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "bcb17fac", - "metadata": {}, - "outputs": [], - "source": [ - "using Printf\n", - "\n", - "x = 2 * floatmin(Float64) # 2*kleinste normalisierte Gleitkommazahl > 0\n", - "\n", - "while x != 0\n", - " x /= 2\n", - " @printf \"%14.6g \" x\n", - " printbitsf64(x)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "658f30b8", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "## Spezielle Werte\n", - "\n", - "Die Gleitkommaarithmetik kennt einige spezielle Werte, z.B.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "576a8b00", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "13628c87", - "metadata": {}, - "outputs": [], - "source": [ - "for x ∈ (NaN, Inf, -Inf, -0.0)\n", - " @printf \"%6g \" x\n", - " printbitsf64(x)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "f79d32eb", - "metadata": {}, - "source": [ - "- Ein Exponentenüberlauf *(overflow)* führt zum Ergebnis `Inf` oder `-Inf`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8b3bf260", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "9f8ae030", - "metadata": {}, - "source": [ - "- Damit kann weitergerechnet werden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f0421f6b", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "b29f956a", - "metadata": {}, - "source": [ - "- `NaN` *(Not a Number)* steht für das Resultat einer Operation, das undefiniert ist. Alle weiteren Operationen mit `NaN` ergeben ebenfalls `NaN`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "28167d92", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "e33dbf1b", - "metadata": {}, - "source": [ - "- Da `NaN` einen undefinierten Wert repräsentiert, ist es zu nichts gleich, nichtmal zu sich selbst. Das ist sinnvoll, denn wenn zwei Variablen `x` und `y` als `NaN` berechnet wurden, sollte man nicht schlußfolgern, dass sie gleich sind. \n", - "- Zum Testen auf `NaN` gibt es daher die boolsche Funktion `isnan()`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d440a247", - "metadata": {}, - "outputs": [], - "source": [ - "x = 0/0\n", - "y = Inf - Inf\n", - "@show x==y NaN==NaN isfinite(NaN) isinf(NaN) isnan(x) isnan(y); " - ] - }, - { - "cell_type": "markdown", - "id": "d63d00e9", - "metadata": {}, - "source": [ - "- Es gibt eine „minus Null“. Sie signalisiert einen Exponentenunterlauf *(underflow)* einer betragsmäßig zu klein gewordenen *negativen* Größe. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2dc5751c", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "68605845", - "metadata": {}, - "source": [ - "## Mathematische Funktionen\n", - "\n", - "Julia verfügt über die [üblichen mathematischen Funktionen](https://docs.julialang.org/en/v1/manual/mathematical-operations/#Rounding-functions) \n", - "`sqrt, exp, log, log2, log10, sin, cos,..., asin, acos,..., sinh,..., gcd, lcm, factorial,...,abs, max, min,...`,\n", - "\n", - "darunter z.B. die [Rundungsfunktionen](https://de.wikipedia.org/wiki/Abrundungsfunktion_und_Aufrundungsfunktion)\n", - "\n", - "- `floor(T,x)` = $\\lfloor x \\rfloor$\n", - "- `ceil(T,x)` = $\\lceil x \\rceil$\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "32b65c0a", - "metadata": {}, - "outputs": [], - "source": [ - "floor(3.4), floor(Int64, 3.5), floor(Int64, -3.5)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c9dbc9e5", - "metadata": {}, - "outputs": [], - "source": [ - "ceil(3.4), ceil(Int64, 3.5), ceil(Int64, -3.5)" - ] - }, - { - "cell_type": "markdown", - "id": "6eba24bc", - "metadata": {}, - "source": [ - "Es sei noch hingewiesen auf `atan(y, x)`, den [Arkustangens mit 2 Argumenten](https://de.wikipedia.org/wiki/Arctan2), Er ist in anderen Programmiersprachen oft als Funktion mit eigenem Namen *atan2* implementiert. \n", - "Dieser löst das Problem der Umrechnung von kartesischen in Polarkoordinaten ohne lästige Fallunterscheidung. \n", - "\n", - "- `atan(y,x)` ist Winkel der Polarkoordinaten von (x,y) im Intervall $(-\\pi,\\pi]$. Im 1. und 4. Quadranten ist er also gleich `atan(y/x)`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1b517f6a", - "metadata": {}, - "outputs": [], - "source": [ - "atan(3, -2), atan(-3, 2), atan(-3/2)" - ] - }, - { - "cell_type": "markdown", - "id": "3f12b1c4", - "metadata": {}, - "source": [ - "## Umwandlung Strings $\\Longleftrightarrow$ Zahlen\n", - "\n", - "Die Umwandlung ist mit den Funktionen `parse()` und `string()` möglich.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "30eaa58a", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cf1565b4", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4c9faf39", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "fa1f5299", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "4bd183df", - "metadata": {}, - "source": [ - "Zur Umwandlung der numerischen Typen ineinander kann man die Typnamen verwenden. Typenamen sind auch Konstruktoren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2022c8ea", - "metadata": {}, - "outputs": [], - "source": [ - "x = Int8(67)\n", - "@show x typeof(x);" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3a8885ab", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "875c77bc", - "metadata": {}, - "outputs": [], - "source": [] - }, - { - "cell_type": "markdown", - "id": "b9d2cb4b", - "metadata": {}, - "source": [ - "## Literatur\n", - "\n", - "- D. Goldberg, [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://www.validlab.com/goldberg/paper.pdf)\n", - "- C. Vuik, [Some Disasters caused by numerical errors](http://ta.twi.tudelft.nl/users/vuik/wi211/disasters.html)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - }, - "language_info": { - "file_extension": ".jl", - "mimetype": "application/julia", - "name": "julia", - "version": "1.10.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/pcomplex.ipynb b/nb/pcomplex.ipynb deleted file mode 100644 index e96abd8..0000000 --- a/nb/pcomplex.ipynb +++ /dev/null @@ -1,989 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "69149570", - "metadata": {}, - "source": [ - "# Ein Fallbeispiel: Der parametrisierte Datentyp PComplex\n", - "\n", - "Wir wollen als neuen numerischen Typen **komplexe Zahlen in Polardarstellung $z=r e^{i\\phi}=(r,ϕ)$** einführen. \n", - "\n", - "- Der Typ soll sich in die Typhierarchie einfügen als Subtyp von 'Number'.\n", - "- $r$ und $\\phi$ sollen Gleitkommazahlen sein. (Im Unterschied zu komplexen Zahlen in 'kartesischen' Koordinaten hat eine Einschränkung auf ganzzahlige Werte von r oder ϕ mathematisch wenig Sinn.)\n", - "\n", - "## Die Definition von `PComplex`\n", - "\n", - "Ein erster Versuch könnte so aussehen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "3ee9c4ae", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "z1 = PComplex1{Float64}(-32.0, 33.0)\n", - "z2 = PComplex1{Float32}(12.0f0, 13.0f0)\n" - ] - } - ], - "source": [ - "struct PComplex1{T <: AbstractFloat} <: Number\n", - " r :: T\n", - " ϕ :: T\n", - "end\n", - "\n", - "z1 = PComplex1(-32.0, 33.0)\n", - "z2 = PComplex1{Float32}(12, 13)\n", - "@show z1 z2;" - ] - }, - { - "cell_type": "markdown", - "id": "729a1d8e", - "metadata": {}, - "source": [ - "Julia stellt automatisch *default constructors* zur Verfügung:\n", - "\n", - "- den Konstruktor `PComplex1`, bei dem der Typ `T` von den übergebenen Argumenten abgeleitet wird und\n", - "- Konstruktoren `PComplex{Float64},...` mit expliziter Typangabe. Hier wird versucht, die Argumente in den angeforderten Typ zu konvertieren. \n", - "\n", - "------\n", - "\n", - "Wir wollen nun, dass der Konstruktor noch mehr tut. \n", - "In der Polardarstellung soll $0\\le r$ und $0\\le \\phi<2\\pi$ gelten.\n", - "\n", - "Wenn die übergebenen Argumente das nicht erfüllen, sollten sie entsprechend umgerechnet werden.\n", - "\n", - "Dazu definieren wir einen _inner constructor_, der den _default constructor_ ersetzt.\n", - "\n", - "- Ein _inner constructor_ ist eine Funktion innerhalb der `struct`-Definition.\n", - "- In einem _inner constructor_ kann man die spezielle Funktion `new` verwenden, die wie der _default constructor_ wirkt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "214480f6", - "metadata": {}, - "outputs": [], - "source": [ - "struct PComplex{T <: AbstractFloat} <: Number\n", - " r :: T\n", - " ϕ :: T\n", - "\n", - " function PComplex{T}(r::T, ϕ::T) where T<:AbstractFloat\n", - " if r<0 # flip the sign of r and correct phi\n", - " r = -r\n", - " ϕ += π\n", - " end\n", - " if r==0 ϕ=0 end # normalize r=0 case to phi=0 \n", - " ϕ = mod(ϕ, 2π) # map phi into interval [0,2pi)\n", - " new(r, ϕ) # new() ist special function,\n", - " end # available only inside inner constructors\n", - "\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "873d5dc6", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: false\n", - "#| output: false\n", - "\n", - "#=\n", - "in den ganzen quarto-runs wollen bir hier noch das default-show benutzen\n", - "=#\n", - "zz = @which Base.show(stdout, PComplex{Float64}(2.,3.))\n", - "if zz.module != Base\n", - " Base.delete_method(zz)\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "95c7386c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PComplex{Float64}(3.3, 1.0)" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z1 = PComplex{Float64}(-3.3, 7π+1)" - ] - }, - { - "cell_type": "markdown", - "id": "eb213995", - "metadata": {}, - "source": [ - "Für die explizite Angabe eines *inner constructors* müssen wir allerdings einen Preis zahlen: Die sonst von Julia bereitgestellten *default constructors* fehlen. \n", - "\n", - "Den Konstruktor, der ohne explizite Typangabe in geschweiften Klammern auskommt und den Typ der Argumente übernimmt, wollen wir gerne auch haben:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "e87d3a42", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PComplex{Float64}(2.0, 0.3)" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "PComplex(r::T, ϕ::T) where {T<:AbstractFloat} = PComplex{T}(r,ϕ)\n", - "\n", - "z2 = PComplex(2.0, 0.3)" - ] - }, - { - "cell_type": "markdown", - "id": "0512b019", - "metadata": {}, - "source": [ - "## Eine neue Schreibweise\n", - "\n", - "Julia verwendet `//` als Infix-Konstruktor für den Typ `Rational`. Sowas Schickes wollen wir auch. \n", - "\n", - "In der Elektronik/Elektrotechnik werden [Wechselstromgrößen durch komplexe Zahlen beschrieben.](https://de.wikipedia.org/wiki/Komplexe_Wechselstromrechnung). Dabei ist eine Darstellung komplexer Zahlen durch \"Betrag\" und \"Phase\" üblich und sie wird gerne in der sogenannten [Versor-Form](https://de.wikipedia.org/wiki/Versor) (engl. *phasor*) dargestellt:\n", - "$$\n", - " z= r\\enclose{phasorangle}{\\phi} = 3.4\\;\\enclose{phasorangle}{45^\\circ}\n", - "$$\n", - "wobei man in der Regel den Winkel in Grad notiert. \n", - "\n", - ":::{.callout-note .titlenormal collapse=\"true\"}\n", - "\n", - "## Mögliche Infix-Operatoren in Julia\n", - "\n", - "In Julia ist eine große Anzahl von Unicode-Zeichen reserviert für die Verwendung als Operatoren. Die definitive Liste ist im [Quellcode des Parsers.](https://github.com/JuliaLang/julia/blob/eaa2c58aeb12f27c1d8c116ab111773a4fc4495f/src/julia-parser.scm#L13-L31)\n", - "\n", - "Auf Details werden wir in einem späteren Kapitel noch eingehen. \n", - "\n", - "Und ja, der Julia-Parser ist in einem Lisp(genauer: Scheme)-Dialekt geschrieben. In Julia ist ein kleiner Scheme-Interpreter namens [femtolisp](https://github.com/JeffBezanson/femtolisp) integriert. Geschrieben hat ihn einer der \"Väter\" von Julia bevor er mit der Arbeit an Julia begann. \n", - "\n", - ":::\n", - "\n", - "Das Winkel-Zeichen `∠` steht leider nicht als Operatorsymbol zur Verfügung. Wir weichen aus auf `⋖`. Das kann in Julia als als `\\lessdot` eingegeben werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "81818d42", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PComplex{Float64}(2.0, 1.5707963267948966)" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - " ⋖(r::Real, ϕ::Real) = PComplex(r, π*ϕ/180)\n", - "\n", - "z3 = 2. ⋖ 90." - ] - }, - { - "cell_type": "markdown", - "id": "bf0863e9", - "metadata": {}, - "source": [ - "(Die Typ-Annotation -- `Real` statt `AbstractFloat` -- ist ein Vorgriff auf kommende weitere Konstruktoren. Im Moment funktioniert der Operator `⋖` erstmal nur mit `Float`s.)\n", - "\n", - "\n", - "Natürlich wollen wir auch die Ausgabe so schön haben. Details dazu findet man in der [Dokumentation](https://docs.julialang.org/en/v1/manual/types/#man-custom-pretty-printing).\n" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "4cf73e28", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "z3 = 2.0⋖90.0°\n" - ] - } - ], - "source": [ - "using Printf\n", - "\n", - "function Base.show(io::IO, z::PComplex)\n", - " # wir drucken die Phase in Grad, auf Zehntelgrad gerundet, \n", - " p = z.ϕ * 180/π\n", - " sp = @sprintf \"%.1f\" p\n", - " print(io, z.r, \"⋖\", sp, '°')\n", - "end\n", - "\n", - "@show z3;" - ] - }, - { - "cell_type": "markdown", - "id": "0dae2fef", - "metadata": {}, - "source": [ - "## Methoden für `PComplex`\n", - "\n", - "Damit unser Typ ein anständiges Mitglied der von `Number` abstammenden Typfamilie wird, brauchen wir allerdings noch eine ganze Menge mehr. Es müssen Arithmetik, Vergleichsoperatoren, Konvertierungen usw. definiert werden. \n", - "\n", - "\n", - "Wir beschränken uns auf Multiplikation und Quadratwurzeln.\n", - "\n", - "\n", - ":::{.callout-note collapse=\"true\"}\n", - "## Module \n", - "\n", - "- Um die `methods` der existierenden Funktionen und Operationen zu ergänzen, muss man diese mit ihrem 'vollen Namen' ansprechen.\n", - "- Alle Objekte gehören zu einem Namensraum oder `module`.\n", - "- Die meisten Basisfunktionen gehören zum Modul `Base`, welches standardmäßig immer ohne explizites `using ...` geladen wird. \n", - "- Solange man keine eigenen Module definiert, sind die eigenen Definitionen im Modul `Main`.\n", - "- Das Macro `@which`, angewendet auf einen Namen, zeigt an, in welchem Modul der Name definiert wurde. \n" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "042418fd", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "Main" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "f(x) = 3x^3\n", - "@which f" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "c20d10e5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Modul für Addition: Base, Modul für sqrt: Base\n" - ] - } - ], - "source": [ - "wp = @which +\n", - "ws = @which(sqrt)\n", - "println(\"Modul für Addition: $wp, Modul für sqrt: $ws\")" - ] - }, - { - "cell_type": "markdown", - "id": "82fe20b4", - "metadata": {}, - "source": [ - ":::\n" - ] - }, - { - "cell_type": "code", - "execution_count": 28, - "id": "a53f0e79", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "qwurzel (generic function with 1 method)" - ] - }, - "execution_count": 28, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "qwurzel(z::PComplex) = PComplex(sqrt(z.r), z.ϕ / 2)" - ] - }, - { - "cell_type": "code", - "execution_count": 29, - "id": "d6987594", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: false\n", - "#| output: false\n", - "\n", - "#=\n", - "damit das length(methods(sqrt)) klappt\n", - "=#\n", - "if hasmethod(sqrt, (PComplex,))\n", - " zz = @which Base.sqrt(PComplex{Float64}(1.,1.))\n", - " Base.delete_method(zz)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "53f4bb77", - "metadata": {}, - "source": [ - "Die Funktion `sqrt()` hat schon einige Methoden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "f93f63c6", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "19" - ] - }, - "execution_count": 30, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "length(methods(sqrt))" - ] - }, - { - "cell_type": "markdown", - "id": "7b4f323a", - "metadata": {}, - "source": [ - "Jetzt wird es eine Methode mehr:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 32, - "id": "b88cd74b", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "20" - ] - }, - "execution_count": 32, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Base.sqrt(z::PComplex) = qwurzel(z)\n", - "\n", - "length(methods(sqrt))" - ] - }, - { - "cell_type": "code", - "execution_count": 33, - "id": "e077b8bf", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "1.4142135623730951⋖8.6°" - ] - }, - "execution_count": 33, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "sqrt(z2)" - ] - }, - { - "cell_type": "markdown", - "id": "e223fdd1", - "metadata": {}, - "source": [ - "und nun zur Multiplikation:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "5537f7ec", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "z1 * z2 = 6.6⋖74.5°\n" - ] - } - ], - "source": [ - "Base.:*(x::PComplex, y::PComplex) = PComplex(x.r * y.r, x.ϕ + y.ϕ)\n", - "\n", - "@show z1 * z2;" - ] - }, - { - "cell_type": "markdown", - "id": "7189f0c6", - "metadata": {}, - "source": [ - "(Da das Operatorsymbol kein normaler Name ist, muss der Doppelpunkt bei der Zusammensetzung mit `Base.` sein.)\n", - "\n", - "Wir können allerdings noch nicht mit anderen numerischen Typen multiplizieren. Dazu könnte man nun eine Vielzahl von entsprechenden Methoden definieren. Julia stellt *für numerische Typen* noch einen weiteren Mechanismus zur Verfügung, der das etwas vereinfacht.\n", - "\n", - "\n", - "## Typ-Promotion und Konversion \n", - "\n", - "In Julia kann man bekanntlich die verschiedensten numerischen Typen nebeneinander verwenden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "610a38fe", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "265.53333333333336" - ] - }, - "execution_count": 14, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "1//3 + 5 + 5.2 + 0xff" - ] - }, - { - "cell_type": "markdown", - "id": "bc39d089", - "metadata": {}, - "source": [ - "Wenn man in die zahlreichen Methoden schaut, die z.B. für `+` und `*` definiert sind, findet man u.a. eine Art 'catch-all-Definition'\n", - "\n", - "```julia\n", - "+(x::Number, y::Number) = +(promote(x,y)...)\n", - "*(x::Number, y::Number) = *(promote(x,y)...)\n", - "```\n", - "\n", - "\n", - "\n", - "(Die 3 Punkte sind der splat-Operator, der das von promote() zurückgegebene Tupel wieder in seine Bestandteile zerlegt.)\n", - "\n", - "Da die Methode mit den Typen `(Number, Number)` sehr allgemein ist, wird sie erst verwendet, wenn spezifischere Methoden nicht greifen.\n", - "\n", - "Was passiert hier?\n", - "\n", - "### Die Funktion `promote(x,y,...)`\n", - "\n", - "Diese Funktion versucht, alle Argumente in einen gemeinsamen Typen umzuwandeln, der alle Werte (möglichst) exakt darstellen kann.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "48cae0ae", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(12.0, 34.555, 0.7777777777777778, 255.0)" - ] - }, - "execution_count": 15, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "promote(12, 34.555, 77/99, 0xff)" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "768934ac", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "z = (33, 27)\n", - "typeof(z) = Tuple{BigInt, BigInt}\n" - ] - } - ], - "source": [ - "z = promote(BigInt(33), 27)\n", - "@show z typeof(z);" - ] - }, - { - "cell_type": "markdown", - "id": "df2672c5", - "metadata": {}, - "source": [ - "Die Funktion `promote()` verwendet dazu zwei Helfer, die Funktionen\n", - " `promote_type(T1, T2)` und `convert(T, x)`\n", - "\n", - "Wie üblich in Julia, kann man diesen Mechanismus durch [eigene *promotion rules* und `convert(T,x)`-Methoden erweitern.](https://docs.julialang.org/en/v1/manual/conversion-and-promotion/) \n", - "\n", - "\n", - "### Die Funktion `promote_type(T1, T2,...)` \n", - "\n", - "Sie ermittelt, zu welchem Typ umgewandelt werden soll. Argumente sind Typen, nicht Werte.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "70306adc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "promote_type(Rational{Int64}, ComplexF64, Float32) = ComplexF64\n" - ] - } - ], - "source": [ - "@show promote_type(Rational{Int64}, ComplexF64, Float32);" - ] - }, - { - "cell_type": "markdown", - "id": "ec999b3a", - "metadata": {}, - "source": [ - "### Die Funktion `convert(T,x)`\n", - "\n", - "Die Methoden von \n", - "`convert(T, x)` wandeln `x` in ein Objekt vom Typ `T` um. Dabei sollte eine solche Umwandlung verlustfrei möglich sein.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "b326a121", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "3.0" - ] - }, - "execution_count": 18, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z = convert(Float64, 3)" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "57606643", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "23" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z = convert(Int64, 23.00)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "a3b39504", - "metadata": {}, - "outputs": [ - { - "ename": "LoadError", - "evalue": "InexactError: Int64(2.3)", - "output_type": "error", - "traceback": [ - "InexactError: Int64(2.3)", - "", - "Stacktrace:", - " [1] Int64", - " @ ./float.jl:912 [inlined]", - " [2] convert(::Type{Int64}, x::Float64)", - " @ Base ./number.jl:7", - " [3] top-level scope", - " @ In[20]:1" - ] - } - ], - "source": [ - "z = convert(Int64, 2.3)" - ] - }, - { - "cell_type": "markdown", - "id": "06251c1d", - "metadata": {}, - "source": [ - "Die spezielle Rolle von `convert()` liegt darin, dass es an verschiedenen Stellen _implizit_ und automatisch eingesetzt wird: \n", - "\n", - "> [The following language constructs call convert](https://docs.julialang.org/en/v1/manual/conversion-and-promotion/#When-is-convert-called?):\n", - "> \n", - " - Assigning to an array converts to the array's element type.\n", - " - Assigning to a field of an object converts to the declared type of the field.\n", - " - Constructing an object with new converts to the object's declared field types.\n", - " - Assigning to a variable with a declared type (e.g. local x::T) converts to that type.\n", - " - A function with a declared return type converts its return value to that type.\n", - "\n", - "-- und natürlich in `promote()`\n", - "\n", - "Für selbstdefinierte Datentypen kann man convert() um weitere Methoden ergänzen.\n", - "\n", - "Für Datentypen innerhalb der Number-Hierarchie gibt es wieder eine 'catch-all-Definition'\n", - "```julia\n", - "convert(::Type{T}, x::Number) where {T<:Number} = T(x)\n", - "```\n", - "\n", - "Also: Wenn für einen Typen `T` aus der Hierarchie `T<:Number` ein Konstruktor `T(x)` mit einem numerischen Argument `x` existiert, dann wird dieser Konstruktor `T(x)` automatisch für Konvertierungen benutzt. (Natürlich können auch speziellere Methoden für `convert()` definiert werden, die dann Vorrang haben.)\n", - "\n", - "\n", - "### Weitere Konstruktoren für `PComplex`\n" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "e258330e", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "PComplex" - ] - }, - "execution_count": 21, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "## (a) r, ϕ beliebige Reals, z.B. Integers, Rationals\n", - "\n", - "PComplex{T}(r::T1, ϕ::T2) where {T<:AbstractFloat, T1<:Real, T2<: Real} = \n", - " PComplex{T}(convert(T, r), convert(T, ϕ))\n", - "\n", - "PComplex(r::T1, ϕ::T2) where {T1<:Real, T2<: Real} = \n", - " PComplex{promote_type(Float64, T1, T2)}(r, ϕ) \n", - "\n", - "## (b) Zur Umwandlung von Reals: Konstruktor mit \n", - "## nur einem Argument r\n", - "\n", - "PComplex{T}(r::S) where {T<:AbstractFloat, S<:Real} = \n", - " PComplex{T}(convert(T, r), convert(T, 0)) \n", - "\n", - "PComplex(r::S) where {S<:Real} = \n", - " PComplex{promote_type(Float64, S)}(r, 0.0)\n", - "\n", - "## (c) Umwandlung Complex -> PComplex\n", - "\n", - "PComplex{T}(z::Complex{S}) where {T<:AbstractFloat, S<:Real} = \n", - " PComplex{T}(abs(z), angle(z))\n", - "\n", - "PComplex(z::Complex{S}) where {S<:Real} = \n", - " PComplex{promote_type(Float64, S)}(abs(z), angle(z))\n" - ] - }, - { - "cell_type": "markdown", - "id": "ccb96089", - "metadata": {}, - "source": [ - "Ein Test der neuen Konstruktoren:\n" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "ec747779", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(0.6⋖45.0°, 1.4142135623730951⋖45.0°, 13.0⋖180.0°)" - ] - }, - "execution_count": 22, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "3//5 ⋖ 45, PComplex(Complex(1,1)), PComplex(-13) " - ] - }, - { - "cell_type": "markdown", - "id": "fd8541cf", - "metadata": {}, - "source": [ - "Wir brauchen nun noch *promotion rules*, die festlegen, welcher Typ bei `promote(x::T1, y::T2)` herauskommen soll. Damit wird `promote_type()` intern um die nötigen weiteren Methoden erweitert. \n", - "\n", - "### *Promotion rules* für `PComplex`\n" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "806fff6a", - "metadata": {}, - "outputs": [], - "source": [ - "Base.promote_rule(::Type{PComplex{T}}, ::Type{S}) where {T<:AbstractFloat,S<:Real} = \n", - " PComplex{promote_type(T,S)}\n", - "\n", - "Base.promote_rule(::Type{PComplex{T}}, ::Type{Complex{S}}) where \n", - " {T<:AbstractFloat,S<:Real} = PComplex{promote_type(T,S)}" - ] - }, - { - "cell_type": "markdown", - "id": "97c7de69", - "metadata": {}, - "source": [ - "1. Regel:\n", - ": Wenn ein `PComplex{T}` und ein `S<:Real` zusammentreffen, dann sollen beide zu `PComplex{U}` umgewandelt werden, wobei `U` der Typ ist, zu dem `S` und `T` beide umgewandelt (_promoted_) werden können. \n", - "\n", - "2. Regel\n", - ": Wenn ein `PComplex{T}` und ein `Complex{S}` zusammentreffen, dann sollen beide zu `PComplex{U}` umgewandelt werden, wobei `U` der Typ ist, zu dem `S` und `T` beide umgewandelt werden können. \n", - "\n", - "\n", - "\n", - "Damit klappt nun die Multiplikation mit beliebigen numerischen Typen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "cc47939d", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(2.0⋖90.0°, 6.0⋖90.0°)" - ] - }, - "execution_count": 25, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "z3, 3z3" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "63c20bc7", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "(43.26661530556787⋖64.0°, 16.970562748477143⋖8.6°)" - ] - }, - "execution_count": 26, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "(3.0+2im) * (12⋖30.3), 12sqrt(z2) " - ] - }, - { - "cell_type": "markdown", - "id": "e94c6b15", - "metadata": {}, - "source": [ - ":::{.callout-caution icon=\"false\" collapse=\"true\" .titlenormal}\n", - "\n", - "## Zusammenfassung: unser Typ `PComplex`\n", - "\n", - "```julia\n", - "struct PComplex{T <: AbstractFloat} <: Number\n", - " r :: T\n", - " ϕ :: T\n", - "\n", - " function PComplex{T}(r::T, ϕ::T) where T<:AbstractFloat\n", - " if r<0 # flip the sign of r and correct phi\n", - " r = -r\n", - " ϕ += π\n", - " end\n", - " if r==0 ϕ=0 end # normalize r=0 case to phi=0 \n", - " ϕ = mod(ϕ, 2π) # map phi into interval [0,2pi)\n", - " new(r, ϕ) # new() ist special function,\n", - " end # available only inside inner constructors\n", - "\n", - "end\n", - "\n", - "# additional constructors\n", - "PComplex(r::T, ϕ::T) where {T<:AbstractFloat} = PComplex{T}(r,ϕ)\n", - "\n", - "\n", - "PComplex{T}(r::T1, ϕ::T2) where {T<:AbstractFloat, T1<:Real, T2<: Real} = \n", - " PComplex{T}(convert(T, r), convert(T, ϕ))\n", - "\n", - "PComplex(r::T1, ϕ::T2) where {T1<:Real, T2<: Real} = \n", - " PComplex{promote_type(Float64, T1, T2)}(r, ϕ) \n", - "\n", - "\n", - "PComplex{T}(r::S) where {T<:AbstractFloat, S<:Real} = \n", - " PComplex{T}(convert(T, r), convert(T, 0)) \n", - "\n", - "PComplex(r::S) where {S<:Real} = \n", - " PComplex{promote_type(Float64, S)}(r, 0.0)\n", - "\n", - "\n", - "PComplex{T}(z::Complex{S}) where {T<:AbstractFloat, S<:Real} = \n", - " PComplex{T}(abs(z), angle(z))\n", - "\n", - "PComplex(z::Complex{S}) where {S<:Real} = \n", - " PComplex{promote_type(Float64, S)}(abs(z), angle(z))\n", - "\n", - "# nice input\n", - "⋖(r::Real, ϕ::Real) = PComplex(r, π*ϕ/180)\n", - "\n", - "# nice output\n", - "using Printf\n", - "\n", - "function Base.show(io::IO, z::PComplex)\n", - " # wir drucken die Phase in Grad, auf Zehntelgrad gerundet, \n", - " p = z.ϕ * 180/π\n", - " sp = @sprintf \"%.1f\" p\n", - " print(io, z.r, \"⋖\", sp, '°')\n", - "end\n", - "\n", - "# arithmetic\n", - "Base.sqrt(z::PComplex) = PComplex(sqrt(z.r), z.ϕ / 2)\n", - "\n", - "Base.:*(x::PComplex, y::PComplex) = PComplex(x.r * y.r, x.ϕ + y.ϕ)\n", - "\n", - "# promotion rules\n", - "Base.promote_rule(::Type{PComplex{T}}, ::Type{S}) where \n", - " {T<:AbstractFloat,S<:Real} = PComplex{promote_type(T,S)}\n", - "\n", - "Base.promote_rule(::Type{PComplex{T}}, ::Type{Complex{S}}) where \n", - " {T<:AbstractFloat,S<:Real} = PComplex{promote_type(T,S)}\n", - "```\n", - ":::\n", - "\n", - ":::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "Jetzt geht sowas wie `PComplex(1, 0)` noch nicht. Wir wollen auch andere reelle Typen für `r` und `ϕ` zulassen. Der Einfachheit halber wandeln wir hier alles nach `Float64` um. Analog verfahren wir auch, wenn nur ein reelles oder komplexes Argument verwendet wird.\n", - "\n", - "```julia\n", - "PComplex(r::Real, ϕ::Real) = PComplex(Float64(r), Float64(ϕ))\n", - "PComplex(r::Real) = PComplex(Float64(r), 0.0)\n", - "PComplex(z::Complex) = PComplex(abs(z), angle(z))\n", - "\n", - "z3 = PComplex(-2); z4 = PComplex(3im)\n", - "@show z3 z4;\n", - "```\n", - "\n", - ":::" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - }, - "language_info": { - "file_extension": ".jl", - "mimetype": "application/julia", - "name": "julia", - "version": "1.10.2" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/script1.sh b/nb/script1.sh deleted file mode 100755 index 30e4c43..0000000 --- a/nb/script1.sh +++ /dev/null @@ -1,8 +0,0 @@ -#!/bin/bash -cp ../chapters/*.quarto_ipynb . -for i in *.quarto_ipynb - do - echo $i - mv $i "${i%.quarto_ipynb}.ipynb" - jupyter nbconvert --inplace --clear-output --to notebook "${i%.quarto_ipynb}.ipynb" - done diff --git a/nb/summary.ipynb b/nb/summary.ipynb deleted file mode 100644 index ba82a9c..0000000 --- a/nb/summary.ipynb +++ /dev/null @@ -1,167 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "bb4361d9", - "metadata": {}, - "source": [ - "---\n", - "title: summary\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "58e5805d", - "metadata": {}, - "source": [ - "format:\n", - " html:\n", - " include-in-header:\n", - " text: |\n", - " \n", - "\n", - "\n", - "https://github.com/JuliaPlots/PlotlyJS.jl/issues/322\n", - "\n", - "In summary, this book has no content whatsoever.\n", - "\n", - "https://discourse.julialang.org/t/seven-lines-of-julia-examples-sought/50416\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "caf6e3b3", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: false\n", - "using PlotlyJS, Random\n", - "using HypertextLiteral\n", - "using JSON, UUIDs\n", - "using Base64\n", - "\n", - "function IJulia.display_dict(p::PlotlyJS.SyncPlot)\n", - " Dict(\n", - " # \"application/vnd.plotly.v1+json\" => JSON.lower(p),\n", - " # \"text/plain\" => sprint(show, \"text/plain\", p),\n", - " \"text/html\" => let\n", - " buf = IOBuffer()\n", - " show(buf, MIME(\"text/html\"), p)\n", - " String(resize!(buf.data, buf.size))\n", - " end,\n", - " \"image/png\" => let\n", - " buf = IOBuffer()\n", - " buf64 = Base64EncodePipe(buf)\n", - " show(buf64, MIME(\"image/png\"), p)\n", - " String(resize!(buf.data, buf.size))\n", - " end,\n", - "\n", - " )\n", - " end\n", - " \n", - " function Base.show(io::IO, mimetype::MIME\"text/html\", p::PlotlyJS.SyncPlot)\n", - " uuid = string(UUIDs.uuid4())\n", - " show(io,mimetype,@htl(\"\"\"\n", - "
\n", - " \n", - "\"\"\"))\n", - "end " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a6260dc2", - "metadata": {}, - "outputs": [], - "source": [ - "Random.seed!(42)\n", - "\n", - "N = 100\n", - "random_x = range(0, stop=1, length=N)\n", - "random_y0 = randn(N) .+ 5\n", - "random_y1 = randn(N)\n", - "random_y2 = randn(N) .- 5\n", - "\n", - "plot([\n", - " scatter(x=random_x, y=random_y0, mode=\"markers\", name=\"markers\"),\n", - " scatter(x=random_x, y=random_y1, mode=\"lines\", name=\"lines\"),\n", - " scatter(x=random_x, y=random_y2, mode=\"markers+lines\", name=\"markers+lines\")\n", - "])" - ] - }, - { - "cell_type": "markdown", - "id": "dd0a1a29", - "metadata": {}, - "source": [ - "jkjkjkj\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "813b97ce", - "metadata": {}, - "outputs": [], - "source": [ - "#| warning: false\n", - "\n", - "plot([\n", - " scatter(x=random_x, y=random_y0, mode=\"markers\", name=\"markers\") ])" - ] - }, - { - "cell_type": "markdown", - "id": "c271b5dc", - "metadata": {}, - "source": [ - ";;l;l;l\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6cb53248", - "metadata": {}, - "outputs": [], - "source": [ - "#| warning: false\n", - "\n", - "plot([\n", - " scatter(x=random_x, y=random_y2, mode=\"markers\", name=\"markers\") ])" - ] - }, - { - "cell_type": "markdown", - "id": "7df06b26", - "metadata": {}, - "source": [ - "lllklk" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.8.5", - "language": "julia", - "name": "julia-1.8" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/syntax.ipynb b/nb/syntax.ipynb deleted file mode 100644 index a02a69f..0000000 --- a/nb/syntax.ipynb +++ /dev/null @@ -1,1185 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "5060b5d0", - "metadata": {}, - "source": [ - "# Grundlagen der Syntax\n", - "\n", - "## Namen von Variablen, Funktionen, Typen etc.\n", - "\n", - "- Namen können Buchstaben, Ziffern, den Unterstrich `_` und das Ausrufezeichen `!` enthalten.\n", - "- Das erste Zeichen muss ein Buchstabe oder ein Unterstrich sein.\n", - "- Groß- und Kleinbuchstaben werden unterschieden: `Nmax` und `NMAX` sind verschiedene Variablen.\n", - "- Als Zeichensatz wird [Unicode](https://home.unicode.org/) verwendet. Damit stehen über 150 Schriften und zahlreiche Symbole zur Verfügung.\n", - "- Es gibt eine kurze [Liste reservierter Schlüsselwörter](https://docs.julialang.org/en/v1/base/base/#Keywords): `if, then, function, true, false,...`\n", - "\n", - ":::{.callout-tip} \n", - "## Beispiel\n", - "\n", - "zulässig: `i, x, Ω, x2, DieUnbekannteZahl, neuer_Wert, 🎷, Zähler, лічильник, einself!!!!,...`\n", - "\n", - "unzulässig: `Uwe's_Funktion, 3achsen, A#B, $this_is_not_Perl, true,...` \n", - ":::\n", - "\n", - "----\n", - "\n", - ":::{.callout-note }\n", - "## Anmerkung \n", - "\n", - "Neben den *reserved keywords* der Kernsprache sind zahlreiche weitere Funktionen und Objekte vordefiniert, wie z.B. die mathematischen Funktionen `sqrt(), log(), sin()`.\n", - "Diese Definitionen finden sich in dem Modul `Base`, welches Julia beim Start automatisch lädt. \n", - "Namen aus `Base` können umdefiniert werden, solange sie noch nicht verwendet wurden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "109cbcf5", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: true \n", - "log = 3\n", - "1 + log" - ] - }, - { - "cell_type": "markdown", - "id": "267dcd3c", - "metadata": {}, - "source": [ - "Jetzt ist natürlich der Logarithmus kaputt:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c8432843", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: true\n", - "x = log(10)" - ] - }, - { - "cell_type": "markdown", - "id": "cf194eb9", - "metadata": {}, - "source": [ - "(siehe auch )\n", - ":::\n", - "\n", - "## Anweisungen\n", - "\n", - "- Im Normalfall enthält eine Zeile eine Anweisung.\n", - "- Wenn eine Anweisung am Zeilenende als unvollständig erkennbar ist durch \n", - " - offene Klammern\n", - " - Operationszeichen,\n", - " \n", - " dann wird die nächste Zeile als Fortsetzung aufgefasst.\n", - "- Mehrere Anweisungen pro Zeile können durch Semikolon getrennt werden.\n", - "- Im interaktiven Betrieb (REPL oder Notebook) unterdrückt ein Semikolon nach der letzten Anweisung die Ausgabe des Ergebnisses dieser Anweisung.\n", - "\n", - ":::{.callout-tip}\n", - "## Beispiel \n", - "\n", - "Im interaktiven Betrieb wird der Wert der letzten Anweisung auch ohne explizites `print()` ausgegeben:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8fa53675", - "metadata": {}, - "outputs": [], - "source": [ - "println(\"Hallo 🌍!\")\n", - "x = sum([i^2 for i=1:10])" - ] - }, - { - "cell_type": "markdown", - "id": "07d1a5e6", - "metadata": {}, - "source": [ - "Das Semikolon unterdrückt das:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4b79202b", - "metadata": {}, - "outputs": [], - "source": [ - "println(\"Hallo 🌍!\")\n", - "x = sum([i^2 for i=1:10]);" - ] - }, - { - "cell_type": "markdown", - "id": "76937fcb", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "---------\n", - "\n", - "\n", - ":::{.callout-warning }\n", - "\n", - "Bei mehrzeiligen Anweisungen muss die fortzusetzende Zeile mit einer offenen Operation oder Klammer enden: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4af8b031", - "metadata": {}, - "outputs": [], - "source": [ - "x = sin(π/2) +\n", - " 3 * cos(0)" - ] - }, - { - "cell_type": "markdown", - "id": "b81c022a", - "metadata": {}, - "source": [ - "Also geht das Folgende schief, aber leider **ohne eine Fehlermeldung**!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "74162af6", - "metadata": {}, - "outputs": [], - "source": [ - "#| error: true\n", - "#| warning: true\n", - "x = sin(π/2)\n", - " + 3 * cos(0)\n", - "println(x)" - ] - }, - { - "cell_type": "markdown", - "id": "fdaa2eed", - "metadata": {}, - "source": [ - "Hier wird das `+` in der zweiten Zeile als Präfix-Operator (Vorzeichen) interpretiert. Damit sind 1. und 2. Zeile jeweils für sich vollständige, korrekte Ausdrücke (auch wenn die 2. Zeile natürlich völlig nutzlos ist) und werden auch so abgearbeitet. \n", - "\n", - "Moral: Wenn man längere Ausdrücke auf mehrere Zeilen aufteilen will, sollte man immer eine Klammer aufmachen. Dann ist egal, wo der Zeilenumbruch ist:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e865958c", - "metadata": {}, - "outputs": [], - "source": [ - "x = ( sin(π/2) \n", - " + 3 * cos(0) )\n", - "println(x)" - ] - }, - { - "cell_type": "markdown", - "id": "ddd2ae7d", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "\n", - "## Kommentare\n", - "\n", - "Julia kennt 2 Arten von Kommentaren im Programmtext:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a628a28a", - "metadata": {}, - "outputs": [], - "source": [ - "# Einzeilige Kommentare beginnen mit einem Doppelkreuz.\n", - "\n", - "x = 2 # alles vom '#' bis zum Zeilenende ist ein Kommentar und wird ignoriert. x = 3" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "39f0f1fd", - "metadata": {}, - "outputs": [], - "source": [ - "#= \n", - " Ein- und mehrzeilige Kommentare können zwischen #= ... =# eingeschlossen werden.\n", - " Dabei sind verschachtelte Kommentare möglich. \n", - " #= \n", - " d.h., anders als in C/C++/Java endet der Kommentar nicht mit dem ersten \n", - " Kommentar-Endezeichen, sondern die #=...=# - Paare wirken wie Klammern. \n", - " =# \n", - " Der automatische 'syntax highlighter' weiss das leider noch nicht, wie die wechselnde \n", - " Graufärbung dieses Kommentars zeigt. \n", - "=#\n", - "\n", - "\n", - "x #= das ist ein seltener Variablenname! =# = 3 " - ] - }, - { - "cell_type": "markdown", - "id": "44aa6359", - "metadata": {}, - "source": [ - "## Datentypen Teil I \n", - "\n", - "- Julia ist eine [stark typisierte](https://de.wikipedia.org/wiki/Starke_Typisierung) Sprache. Alle Objekte haben einen Typ. Funktionen/Operationen erwarten Argumente mit dem richtigen Typ.\n", - "- Julia ist eine [dynamisch typisierte](https://de.wikipedia.org/wiki/Dynamische_Typisierung) Sprache. Variablen haben keinen Typ. Sie sind Namen, die durch Zuweisung `x = ...` an Objekte gebunden werden können.\n", - "- Wenn man vom „Typ einer Variablen“ spricht, meint man den Typ des Objektes, das der Variablen gerade zugewiesen ist.\n", - "- Funktionen/Operatoren können verschiedene *methods* für verschiedene Argumenttypen implementieren.\n", - "- Abhängig von den konkreten Argumenttypen wird dann bei Verwendung einer Funktion entschieden, welche Methode benutzt wird ([*dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch)).\n", - "\n", - "\n", - "Einfache Basistypen sind z.B.:\n", - "\n", - "```\n", - "Int64, Float64, String, Char, Bool\n", - "```\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f5fcc67a", - "metadata": {}, - "outputs": [], - "source": [ - "x = 2\n", - "x, typeof(x), sizeof(x) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0f4c6d58", - "metadata": {}, - "outputs": [], - "source": [ - "x = 0.2\n", - "x, typeof(x), sizeof(x) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ef084989", - "metadata": {}, - "outputs": [], - "source": [ - "x = \"Hallo!\"\n", - "x, typeof(x), sizeof(x) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1f1df8fc", - "metadata": {}, - "outputs": [], - "source": [ - "x = 'Ω'\n", - "x, typeof(x), sizeof(x) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b833e181", - "metadata": {}, - "outputs": [], - "source": [ - "x = 3 > π\n", - "x, typeof(x), sizeof(x) " - ] - }, - { - "cell_type": "markdown", - "id": "610935f8", - "metadata": {}, - "source": [ - "- `sizeof()` liefert die Größe eines Objekts oder Typs in Bytes (1 Byte = 8 Bit)\n", - "- 64bit Ganzzahlen und 64bit Gleitkommazahlen entsprechen dem Befehlssatz moderner Prozessoren und sind daher die numerischen Standardtypen.\n", - "- Zeichen/*chars* `'A'` und Zeichenketten/*strings* `\"A\"` der Länge 1 sind verschiedene Objekte. \n", - "\n", - "## Ablaufsteuerung\n", - "\n", - "### `if`-Blöcke\n", - "\n", - "- Ein `if`-Block *kann* **beliebig viele** `elseif`-Zweige und als letztes maximal **einen** `else`-Zweig enthalten.\n", - "- Der Block hat einen Wert, den Wert der letzten ausgeführten Anweisung.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1b399845", - "metadata": {}, - "outputs": [], - "source": [ - "x = 33\n", - "y = 44\n", - "z = 34\n", - "\n", - "if x < y && z != x # elseif- und else-Blöcke sind optional\n", - " println(\"yes\")\n", - " x += 10\n", - "elseif x < z # beliebig viele elseif-Blöcke\n", - " println(\" x is smaller than z\")\n", - "elseif x == z+1 \n", - " println(\" x is successor of z\")\n", - "else # maximal ein else-Block \n", - " println(\"Alles falsch\")\n", - "end # Wert des gesamten Blocks ist der Wert der \n", - " # letzten ausgeführten Auswertung" - ] - }, - { - "cell_type": "markdown", - "id": "73a859d9", - "metadata": {}, - "source": [ - "Kurze Blöcke kann man in eine Zeile schreiben:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ad94abc7", - "metadata": {}, - "outputs": [], - "source": [ - "if x > 10 println(\"x is larger than 10\") end " - ] - }, - { - "cell_type": "markdown", - "id": "34c18e6c", - "metadata": {}, - "source": [ - "Der Wert eines `if`-Blocks kann natürlich zugewiesen werden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "27eef305", - "metadata": {}, - "outputs": [], - "source": [ - "y = 33\n", - "z = if y > 10 \n", - " println(\"y is larger than 10\") \n", - " y += 1 \n", - " end\n", - "z " - ] - }, - { - "cell_type": "markdown", - "id": "0ac5ece1", - "metadata": {}, - "source": [ - "### Auswahloperator (ternary operator) `test ? exp1 : exp2`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "dbe58322", - "metadata": {}, - "outputs": [], - "source": [ - "x = 20\n", - "y = 15\n", - "z = x < y ? x+1 : y+1" - ] - }, - { - "cell_type": "markdown", - "id": "d7e0a7f9", - "metadata": {}, - "source": [ - "ist äquivalent zu\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e1929004", - "metadata": {}, - "outputs": [], - "source": [ - "z = if x < y\n", - " x+1\n", - " else\n", - " y+1\n", - " end" - ] - }, - { - "cell_type": "markdown", - "id": "406f03e8", - "metadata": {}, - "source": [ - "## Vergleiche, Tests, Logische Operationen\n", - "\n", - "### Arithmetische Vergleiche\n", - "\n", - "- `==`\n", - "- `!=`, `≠`\n", - "- `>`\n", - "- `>=`, `≥`\n", - "- `<`\n", - "- `<=`, `≤`\n", - "\n", - "Wie üblich, ist der Test auf Gleichheit `==` vom Zuweisungsoperator `=` zu unterscheiden. Vergleichen lässt sich so gut wie alles:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5409328f", - "metadata": {}, - "outputs": [], - "source": [ - "\"Aachen\" < \"Leipzig\", 10 ≤ 10.01, [3,4,5] < [3,6,2]" - ] - }, - { - "cell_type": "markdown", - "id": "9b27b690", - "metadata": {}, - "source": [ - "Nun ja, fast alles:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "5e6b4540", - "metadata": {}, - "outputs": [], - "source": [ - "3 < \"vier\"" - ] - }, - { - "cell_type": "markdown", - "id": "df810fec", - "metadata": {}, - "source": [ - "Die Fehlermeldung zeigt ein paar Grundprinzipien von Julia:\n", - "\n", - "- Operatoren sind auch nur Funktionen: `x < y` wird zum Funktionsaufruf `isless(x, y)`.\n", - "- Funktionen (und damit Operatoren) können verschiedene *methods* für verschiedene Argumenttypen implementieren. \n", - "- Abhängig von den konkreten Argumenttypen wird beim Aufruf der Funktion entschieden, welche Methode benutzt wird ([*dynamic dispatch*](https://en.wikipedia.org/wiki/Dynamic_dispatch)).\n", - "\n", - "Man kann sich alle Methoden zu einer Funktion anzeigen lassen. Das gibt einen Einblick in das komplexe Typssystem von Julia:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "aa2d90be", - "metadata": {}, - "outputs": [], - "source": [ - "methods(<)" - ] - }, - { - "cell_type": "markdown", - "id": "7d79d348", - "metadata": {}, - "source": [ - "Zuletzt noch: Vergleiche können gekettet werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3de7f381", - "metadata": {}, - "outputs": [], - "source": [ - "10 < x ≤ 100 # das ist äquivalent zu\n", - " # 10 < x && x ≤ 100" - ] - }, - { - "cell_type": "markdown", - "id": "e5535e05", - "metadata": {}, - "source": [ - "### Tests \n", - "Einge Funktionen vom Typ `f(c::Char) -> Bool`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1fa42721", - "metadata": {}, - "outputs": [], - "source": [ - "isnumeric('a'), isnumeric('7'), isletter('a')" - ] - }, - { - "cell_type": "markdown", - "id": "9e3772fc", - "metadata": {}, - "source": [ - "und vom Typ `f(s1::String, s2::String) -> Bool`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a462d33f", - "metadata": {}, - "outputs": [], - "source": [ - "contains(\"Lampenschirm\", \"pensch\"), startswith(\"Lampenschirm\", \"Lamb\"), endswith(\"Lampenschirm\", \"rm\")" - ] - }, - { - "cell_type": "markdown", - "id": "ee1487a3", - "metadata": {}, - "source": [ - "- Die Funktion `in(item, collection) -> Bool` testet, ob `item` in `collection` ist. \n", - "- Sie hat auch das Alias ` ∈(item, collection)` und \n", - "- sowohl `in` als auch `∈` können auch als Infix-Operatoren geschrieben werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "71790111", - "metadata": {}, - "outputs": [], - "source": [ - "x = 3\n", - "x in [1, 2, 3, 4, 5]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9b92ce4", - "metadata": {}, - "outputs": [], - "source": [ - "x ∈ [1, 2, 33, 4, 5]" - ] - }, - { - "cell_type": "markdown", - "id": "93782274", - "metadata": {}, - "source": [ - "### Logische Operationen: `&&`, `||`, `!`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8e907712", - "metadata": {}, - "outputs": [], - "source": [ - "3 < 4 && !(2 > 8) && !contains(\"aaa\", \"b\")" - ] - }, - { - "cell_type": "markdown", - "id": "efb19c75", - "metadata": {}, - "source": [ - "#### Bedingte Auswertung (_short circuit evaluation_)\n", - "\n", - "- in `a && b` wird `b` nur ausgewertet, wenn `a == true`\n", - "- in `a || b` wird `b` nur ausgewertet, wenn `a == false`\n", - "\n", - "(i) Damit kann `if test statement end` auch als `test && statement` geschrieben werden.\n", - "\n", - "(ii) Damit kann `if !test statement end` als `test || statement` geschrieben werden.\n", - "\n", - "Als Beispiel^[aus der [Julia-Dokumentation](https://docs.julialang.org/en/v1/manual/control-flow/#Short-Circuit-Evaluation)] hier eine Implementierung der Fakultätsfunktion *(factorial)*:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e5cae687", - "metadata": {}, - "outputs": [], - "source": [ - "function fact(n::Int)\n", - " n >= 0 || error(\"n must be non-negative\")\n", - " n == 0 && return 1\n", - " n * fact(n-1)\n", - "end\n", - "\n", - "fact(5)" - ] - }, - { - "cell_type": "markdown", - "id": "444d49b9", - "metadata": {}, - "source": [ - "Natürlich kann man alle diese Tests auch Variablen vom Typ `Bool` zuordnen und\n", - "diese Variablen können als Tests in `if`- und `while`-Blöcken verwendet werden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "68a69b63", - "metadata": {}, - "outputs": [], - "source": [ - "x = 3 < 4\n", - "y = 5 ∈ [1, 2, 5, 7]\n", - "z = x && y\n", - "if z # äquivalent zu: if 3 < 4 && 5 in [1,2,5,7]\n", - " println(\"Stimmt alles!\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "e42d40c8", - "metadata": {}, - "source": [ - "- In Julia müssen alle Tests in einem logischen Ausdruck vom Typ `Bool` sein.\n", - "- Es gibt keine implizite Konvertierung à la *\"0 is false and 1 (or anything != 0) is true\"*\n", - "- Wenn `x` ein numerischer Typ ist, dann muss daher das C-Idiom `if(x)` als `if x != 0` geschrieben werden.\n", - "- Es gibt eine Ausnahme zur Unterstützung der _short circuit evaluation_:\n", - " - bei den Konstrukten `a && b && c...` bzw `a || b || c...` muss der letzte Teilausdruck nicht vom Typ `Bool` sein, wenn diese Konstrukte nicht als Tests in `if` oder `while` verwendet werden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9fb43a4a", - "metadata": {}, - "outputs": [], - "source": [ - "z = 3 < 4 && 10 < 5 && sqrt(3^3)\n", - "z, typeof(z)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "58faddd6", - "metadata": {}, - "outputs": [], - "source": [ - "z = 3 < 4 && 10 < 50 && sqrt(3^3)\n", - "z, typeof(z)" - ] - }, - { - "cell_type": "markdown", - "id": "295ec49e", - "metadata": {}, - "source": [ - "## Schleifen *(loops)*\n", - "\n", - "### Die `while` (\"solange\")-Schleife\n", - "\n", - "\n", - "Syntax:\n", - "```\n", - "while *condition*\n", - " *loop body*\n", - "end\n", - "```\n", - "Eine Reihe von Anweisungen (der Schleifenkörper) wird immer wieder abgearbeitet, solange eine Bedingung erfüllt ist.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9bd613c4", - "metadata": {}, - "outputs": [], - "source": [ - "i = 1 # typischerweise braucht der Test der \n", - " # while-Schleife eine Vorbereitung ...\n", - "while i < 10 \n", - " println(i)\n", - " i += 2 # ... und ein update\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "33b95f6d", - "metadata": {}, - "source": [ - "Der Körper einer `while`- und `for`-Schleife kann die Anweisungen `break` und `continue` enthalten. `break` stoppt die Schleife, `continue` überspringt den Rest des Schleifenkörpers und beginnt sofort mit dem nächsten Schleifendurchlauf.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8ef0e09b", - "metadata": {}, - "outputs": [], - "source": [ - "i = 0\n", - "\n", - "while i<10\n", - " i += 1\n", - "\n", - " if i == 3\n", - " continue # beginne sofort nächsten Durchlauf,\n", - " end # überspringe Rest des Schleifenkörpers\n", - "\n", - " println(\"i = $i\")\n", - "\n", - " if i ≥ 5\n", - " break # breche Schleife ab\n", - " end\n", - "end\n", - "\n", - "println(\"Fertig!\")" - ] - }, - { - "cell_type": "markdown", - "id": "ab77d5c1", - "metadata": {}, - "source": [ - "Mit `break` kann man auch Endlosschleifen verlassen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "72307342", - "metadata": {}, - "outputs": [], - "source": [ - "i = 1\n", - "\n", - "while true\n", - " println(2^i)\n", - " i += 1\n", - " if i > 8 break end\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "f3032c94", - "metadata": {}, - "source": [ - "### `for`-Schleifen\n", - "\n", - "Syntax:\n", - "\n", - "```\n", - "for *var* in *iterable container*\n", - " *loop body*\n", - "end\n", - "```\n", - "\n", - "Der Schleifenkörper wird für alle Items aus einem Container durchlaufen. \n", - "\n", - "Statt `in` kann immer auch $\\in$ verwendet werden. Im Kopf einer `for`-Schleife kann auch `=` verwendet werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1e45bf78", - "metadata": {}, - "outputs": [], - "source": [ - "for i ∈ [\"Mutter\", \"Vater\", \"Tochter\"]\n", - " println(i)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "e723c97a", - "metadata": {}, - "source": [ - "Oft benötigt man einen numerischen Schleifenzähler. Dafür gibt es das *range*-Konstrukt. Die einfachsten Formen sind \n", - "`Start:Ende` und `Start:Schrittweite:Ende`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b3a01bd4", - "metadata": {}, - "outputs": [], - "source": [ - "endwert = 5\n", - "\n", - "for i ∈ 1:endwert\n", - " println(i^2)\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8427a301", - "metadata": {}, - "outputs": [], - "source": [ - "for i = 1:5.5 print(\" $i\") end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f973a1cb", - "metadata": {}, - "outputs": [], - "source": [ - "for i = 1:2:14 print(\" $i\") end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "63290cd9", - "metadata": {}, - "outputs": [], - "source": [ - "for k = 14 : -2.5 : 1 print(\" $k\") end" - ] - }, - { - "cell_type": "markdown", - "id": "419963f0", - "metadata": {}, - "source": [ - "#### Geschachtelte Schleifen _(nested loops)_\n", - "\n", - "Ein `break` beendet die innerste Schleife.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "06ab8236", - "metadata": {}, - "outputs": [], - "source": [ - "for i = 1:3\n", - " for j = 1:3\n", - " println( (i,j) )\n", - " if j == 2\n", - " break\n", - " end\n", - " end\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "19464d7e", - "metadata": {}, - "source": [ - "Man kann *nested loops* auch in einer `for`-Anweisung zusammenfassen. Dann beendet ein `break` die Gesamtschleife.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e208b54c", - "metadata": {}, - "outputs": [], - "source": [ - "for i = 1:3, j=1:3 # im Prinzip dasselbe wie oben, aber:\n", - " println( (i,j) )\n", - " if j == 2\n", - " break # break bricht hier die Gesamtschleife ab\n", - " end\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "e5f41344", - "metadata": {}, - "source": [ - ":::{.callout-important .titlenormalxx}\n", - "## **Wichtig:** Die Semantik ist völlig anders, als bei C-artigen `for`-Schleifen!\n", - "\n", - "**Bei jedem Schleifendurchlauf wird die Laufvariable neu mit dem nächsten Element aus dem Container initialisiert.**\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c903a887", - "metadata": {}, - "outputs": [], - "source": [ - "for i = 1:5\n", - " print(i,\" ... \")\n", - " i += 2\n", - " println(i)\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "68db2918", - "metadata": {}, - "source": [ - "-------\n", - "\n", - "Die C-Semantik von `for(i=1; i<5; i++)` entspricht der `while`-Schleife:\n", - "```\n", - "i = 1\n", - "while i<5\n", - " *loop body* # hier kann auch wirksam an i rumgepfuscht werden\n", - " i += 1\n", - "end\n", - "```\n", - ":::\n", - "\n", - "## Unicode \n", - "\n", - "Julia verwendet Unicode als Zeichensatz. Damit können für Variablen, Funktionen etc auch Bezeichner aus nicht-lateinischen Schriften (zB Kyrillisch, Koreanisch, Sanskrit, Runen,\n", - "Emoji,...) verwendet werden. Die Frage, wie man solche Zeichen in seinem Editor eingeben kann und ob der verwendete Bildschirm-Font sie darstellen kann, ist nicht Julias Problem.\n", - "\n", - "- Einige Unicode-Zeichen, z.B. `≤, ≠, ≥, π, ∈, √`, können anstelle von `<=, !=, >=, pi, in, sqrt` verwendet werden. \n", - "\n", - "- über 3000 Unicode-Zeichen können in Julia in einer LaTeX-ähnlichen Weise mit der Tab-Vervollständigung eingegeben werden. \n", - " - `\\alpha` wird zu `α`, \n", - " - `\\euler` wird zu `ℯ` (Eulersche Zahl `exp(1)`, [spezielles Schreibschrift-e, `U+0212F`](https://www.htmlsymbol.com/unicode-code/212f.html))\n", - " - `\\le` wird zu `≤`,\n", - " - `\\in` wird zu `∈`,\n", - " - `\\:rainbow:` wird zu `🌈` \n", - " [Hier geht es zur Liste.](https://docs.julialang.org/en/v1/manual/unicode-input/)\n", - "\n", - "## Eigenheiten und Stolperfallen der Syntax\n", - "\n", - "- Man kann den Multiplikationsoperator `*` nach einer numerischen Konstanten weglassen, wenn eine Variable, Funktion oder öffnende Klammer folgt.\n", - " ```\n", - " z = 3.4x + 2(x+y) + xy\n", - " ```\n", - "\n", - "ist daher korrektes Julia. Beachte allerdings, dass der Term `xy` als eine Variable mit dem Namen xy interpretiert wird __und nicht__ als Produkt von x und y!\n", - "\n", - "- Diese Regel hat ein paar Tücken:\n", - "\n", - "Das funktioniert wie erwartet:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6b3cf482", - "metadata": {}, - "outputs": [], - "source": [ - "e = 7\n", - "3e " - ] - }, - { - "cell_type": "markdown", - "id": "2009bbff", - "metadata": {}, - "source": [ - "Hier wird die Eingabe als Gleitkommazahl interpretiert -- und `3E+2` oder `3f+2` (Float32) ebenso. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d1812cfd", - "metadata": {}, - "outputs": [], - "source": [ - "3e+2 " - ] - }, - { - "cell_type": "markdown", - "id": "6cf09a01", - "metadata": {}, - "source": [ - "Ein Leerzeichen schafft Eindeutigkeit:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e6104540", - "metadata": {}, - "outputs": [], - "source": [ - "3e + 2 " - ] - }, - { - "cell_type": "markdown", - "id": "5215cde4", - "metadata": {}, - "source": [ - "Das funktioniert:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6828cede", - "metadata": {}, - "outputs": [], - "source": [ - "x = 4\n", - "3x + 3 " - ] - }, - { - "cell_type": "markdown", - "id": "5316e342", - "metadata": {}, - "source": [ - "...und das nicht. `0x`, `0o`, `0b` wird als Anfang einer Hexadezimal-, Oktal- bzw. Binärkonstanten interpretiert.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d8ff4514", - "metadata": {}, - "outputs": [], - "source": [ - "3y + 0x " - ] - }, - { - "cell_type": "markdown", - "id": "d2df69d1", - "metadata": {}, - "source": [ - "- Es gibt noch ein paar andere Fälle, bei denen die sehr kulante Syntax zu Überraschungen führt.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "02e802cf", - "metadata": {}, - "outputs": [], - "source": [ - "Wichtig = 21\n", - "Wichtig! = 42 # Bezeichner können auch ein ! enthalten\n", - "(Wichtig, Wichtig!)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "227c2b1d", - "metadata": {}, - "outputs": [], - "source": [ - "Wichtig!=88" - ] - }, - { - "cell_type": "markdown", - "id": "b14d28e3", - "metadata": {}, - "source": [ - "Julia interpretiert das als Vergleich `Wichtig != 88`.\n", - "\n", - "Leerzeichen helfen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "41460c8d", - "metadata": {}, - "outputs": [], - "source": [ - "Wichtig! = 88\n", - "Wichtig!" - ] - }, - { - "cell_type": "markdown", - "id": "8c7a3ede", - "metadata": {}, - "source": [ - "- Operatoren der Form `.*`, `.+`,... haben in Julia eine spezielle Bedeutung (*broadcasting*, d.h., vektorisierte Operationen). \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1d6f31aa", - "metadata": {}, - "outputs": [], - "source": [ - "1.+2." - ] - }, - { - "cell_type": "markdown", - "id": "1ffdeba1", - "metadata": {}, - "source": [ - "Wieder gilt: Leerzeichen schaffen Klarheit!\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "350fe2e3", - "metadata": {}, - "outputs": [], - "source": [ - "1. + 2." - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/nb/types.ipynb b/nb/types.ipynb deleted file mode 100644 index 7044cc2..0000000 --- a/nb/types.ipynb +++ /dev/null @@ -1,1497 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "id": "782b49af", - "metadata": {}, - "source": [ - "---\n", - "notebook-links: false\n", - "---" - ] - }, - { - "cell_type": "markdown", - "id": "8a4cf30f", - "metadata": {}, - "source": [ - "# Das Typsystem von Julia\n", - "\n", - "Man kann umfangreiche Programme in Julia schreiben, ohne auch nur eine einzige Typdeklaration verwenden zu müssen. Das ist natürlich Absicht und soll die Arbeit der Anwender vereinfachen.\n", - "\n", - "Wir blicken jetzt trotzdem mal unter die Motorhaube.\n", - "\n", - "## Die Typhierarchie am Beispiel der numerischen Typen\n", - "\n", - "Das Typsystem hat die Struktur eines Baums, dessen Wurzel der Typ `Any` ist. Mit den Funktionen `subtypes()` und `supertype()` kann man den Baum erforschen. Sie zeigen alle Kinder bzw. die Mutter eines Knotens an.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c657afef", - "metadata": {}, - "outputs": [], - "source": [ - "subtypes(Int64)" - ] - }, - { - "cell_type": "markdown", - "id": "34cfce26", - "metadata": {}, - "source": [ - "Das Ergebnis ist eine leere Liste von Typen. `Int64` ist ein sogenannter **konkreter Typ** und hat keine Untertypen.\n", - "\n", - "Wir klettern jetzt mal die Typhierarchie auf diesem Ast nach oben bis zur Wurzel (Informatiker-Bäume stehen bekanntlich immer auf dem Kopf).\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a45cb2eb", - "metadata": {}, - "outputs": [], - "source": [ - "supertype(Int64)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3ccc88af", - "metadata": {}, - "outputs": [], - "source": [ - "supertype(Signed)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c368a69d", - "metadata": {}, - "outputs": [], - "source": [ - "supertype(Integer)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "31ff03ae", - "metadata": {}, - "outputs": [], - "source": [ - "supertype(Real)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "96315571", - "metadata": {}, - "outputs": [], - "source": [ - "supertype(Number)" - ] - }, - { - "cell_type": "markdown", - "id": "86acca0c", - "metadata": {}, - "source": [ - "Das wäre übrigens auch schneller gegangen: Die Funktion `supertypes()` (mit Plural-s) zeigt alle Vorfahren an.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "550adea0", - "metadata": {}, - "outputs": [], - "source": [ - "supertypes(Int64)" - ] - }, - { - "cell_type": "markdown", - "id": "8ba10cd3", - "metadata": {}, - "source": [ - "Nun kann man sich die Knoten angucken:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "{{< embed ../notebooks/nb-types.ipynb#nb3 >}}\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "Mit einer kleinen rekursiven Funktion kann man schnell einen ganzen (Unter-)Baum ausdrucken: \n", - "\n", - "\n", - "\n", - "\n", - "\n", - "{{< embed ../notebooks/nb-types.ipynb#nb1 >}}\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "::::{.content-hidden unless-format=\"xxx\"}\n", - "\n", - "...und natürlich gibt es da auch ein Julia-Paket:\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "{{< embed ../notebooks/nb-types.ipynb#nb2 >}}\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - "\n", - ":::\n", - "\n", - "\n", - "Hier das Ganze nochmal als Bild (gemacht mit LaTeX/[TikZ](https://tikz.dev/tikz-trees))\n", - "\n", - "::: {.content-visible when-format=\"html\"}\n", - "![](../images/TypeTree2.png){width=80%}\n", - ":::\n", - "\n", - "::: {.content-visible when-format=\"pdf\"}\n", - "![Die Hierarchie der numerischen Typen](../images/TypeTree2.png){width=60%}\n", - ":::\n", - "\n", - "\n", - "Natürlich hat Julia nicht nur numerische Typen. Die Anzahl der direkten Abkömmlinge (Kinder) von `Any` ist\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "1bd31bf7", - "metadata": {}, - "outputs": [], - "source": [ - "length(subtypes(Any))" - ] - }, - { - "cell_type": "markdown", - "id": "46ea6703", - "metadata": {}, - "source": [ - "und mit (fast) jedem Paket, das man mit `using ...` lädt, werden es mehr.\n", - "\n", - "\n", - "## Abstrakte und Konkrete Typen\n", - "\n", - "- Ein Objekt hat immer einen **konkreten** Typ. \n", - "- Konkrete Typen haben keine Untertypen mehr, sie sind immer „Blätter“ des Baumes.\n", - "- Konkrete Typen spezifizieren eine konkrete Datenstruktur.\n", - "\n", - ":::{.xxx}\n", - "\n", - ":::\n", - "\n", - "- Abstrakte Typen können nicht instanziiert werden, d.h., es gibt keine Objekte mit diesem Typ. \n", - "- Sie definieren eine Menge von konkreten Typen und gemeinsame Methoden für diese Typen.\n", - "- Sie können daher in der Definition von Funktionstypen, Argumenttypen, Elementtypen von zusammengesetzten Typen u.ä. verwendet werden.\n", - "\n", - "\n", - "\n", - "Zum **Deklarieren** *und* **Testen** der \"Abstammung\" innerhalb der Typhierarchie gibt es einen eigenen Operator:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b8b10ed6", - "metadata": {}, - "outputs": [], - "source": [ - "Int64 <: Number " - ] - }, - { - "cell_type": "markdown", - "id": "9c8bd208", - "metadata": {}, - "source": [ - "Zum Testen, ob ein Objekt einen bestimmten Typ (oder einen abstrakten Supertyp davon) hat, dient `isa(object, typ)`. Es wird meist in der Infix-Form verwendet und sollte als Frage `x is a T?` gelesen werden.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "87663e4e", - "metadata": {}, - "outputs": [], - "source": [ - "x = 17.2\n", - "\n", - "42 isa Int64, 42 isa Real, x isa Real, x isa Float64, x isa Integer " - ] - }, - { - "cell_type": "markdown", - "id": "2f627b1b", - "metadata": {}, - "source": [ - "Da abstrakte Typen keine Datenstrukturen definieren, ist ihre Definition recht schlicht. Entweder sie stammen direkt von `Any` ab:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0419b2c6", - "metadata": {}, - "outputs": [], - "source": [ - "abstract type MySuperType end\n", - "\n", - "supertype(MySuperType)" - ] - }, - { - "cell_type": "markdown", - "id": "68448b69", - "metadata": {}, - "source": [ - "oder von einem anderen abstrakten Typ:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "6ab6c2a6", - "metadata": {}, - "outputs": [], - "source": [ - "abstract type MySpecialNumber <: Integer end\n", - "\n", - "supertypes(MySpecialNumber)" - ] - }, - { - "cell_type": "markdown", - "id": "a1b16c28", - "metadata": {}, - "source": [ - "## Die numerischen Typen `Bool` und `Irrational` \n", - "\n", - "Da sie im Baum der numerischen Typen zu sehen sind, seien sie kurz erklärt: \n", - "\n", - "`Bool` ist numerisch im Sinne von `true=1, false=0`: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c991dbbe", - "metadata": {}, - "outputs": [], - "source": [ - "true + true + true, false - true, sqrt(true), true/4" - ] - }, - { - "cell_type": "markdown", - "id": "9cc6bf10", - "metadata": {}, - "source": [ - "`Irrational` ist der Typ einiger vordefinierter Konstanten wie `π` und `ℯ`. \n", - "Laut [Dokumentation](https://docs.julialang.org/en/v1/base/numbers/#Base.AbstractIrrational) ist `Irrational` ein *\"Number type representing an exact irrational value, which is automatically rounded to the correct precision in arithmetic operations with other numeric quantities\".*\n", - "\n", - "## Union-Typen\n", - "\n", - "Falls die Baum-Hierarchie nicht ausreicht, kann man auch abstrakte Typen als Vereinigung beliebiger (abstrakter und konkreter) Typen definieren.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "b3af8cf9", - "metadata": {}, - "outputs": [], - "source": [ - "IntOrString = Union{Int64,String}" - ] - }, - { - "cell_type": "markdown", - "id": "6b304c6b", - "metadata": {}, - "source": [ - ":::{.callout-note .titlenormal}\n", - "\n", - "## Beispiel\n", - "Das Kommando `methods(<)` zeigt, dass unter den über 70 Methoden, die für den Vergleichsoperator definiert sind, einige auch *union types* verwenden, z.B. ist\n", - "```julia\n", - " <(x::Union{Float16, Float32, Float64}, y::BigFloat)\n", - "```\n", - "eine Methode für den Vergleich einer Maschinenzahl fester Länge mit einer Maschinenzahl beliebiger Länge. \n", - ":::\n", - "\n", - "## Zusammengesetzte (_composite_) Typen: `struct`\n", - "\n", - "Eine `struct` ist eine Zusammenstellung von mehreren benannten Feldern und definiert einen konkreten Typ.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "38f2a5ab", - "metadata": {}, - "outputs": [], - "source": [ - "abstract type Point end\n", - "\n", - "mutable struct Point2D <: Point\n", - " x :: Float64\n", - " y :: Float64\n", - "end\n", - "\n", - "mutable struct Point3D <: Point\n", - " x :: Float64\n", - " y :: Float64\n", - " z :: Float64\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "0a7b8685", - "metadata": {}, - "source": [ - "Wie wir schon bei Ausdrücken der Form `x = Int8(33)` gesehen haben, kann man Typnamen direkt als Konstruktoren einsetzen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cfd64912", - "metadata": {}, - "outputs": [], - "source": [ - "p1 = Point2D(1.4, 3.5)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "107ba10e", - "metadata": {}, - "outputs": [], - "source": [ - "p1 isa Point3D, p1 isa Point2D, p1 isa Point" - ] - }, - { - "cell_type": "markdown", - "id": "e96471e5", - "metadata": {}, - "source": [ - "Die Felder einer `struct` können über ihren Namen mit dem `.`-Operator adressiert werden. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0e672e78", - "metadata": {}, - "outputs": [], - "source": [ - "p1.y" - ] - }, - { - "cell_type": "markdown", - "id": "5614cb89", - "metadata": {}, - "source": [ - "Da wir unsere `struct` als `mutable` deklariert haben, können wir das Objekt `p1` modifizieren, indem wir den Feldern neue Werte zuweisen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "cd6e9ae8", - "metadata": {}, - "outputs": [], - "source": [ - "p1.x = 3333.4\n", - "p1" - ] - }, - { - "cell_type": "markdown", - "id": "1686641e", - "metadata": {}, - "source": [ - "Informationen über den Aufbau eines Typs oder eines Objekts von diesem Typ liefert `dump()`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "29deb4f7", - "metadata": {}, - "outputs": [], - "source": [ - "dump(Point3D) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d07356bc", - "metadata": {}, - "outputs": [], - "source": [ - " dump(p1)" - ] - }, - { - "cell_type": "markdown", - "id": "e02a2f66", - "metadata": {}, - "source": [ - "## Funktionen und *Multiple dispatch*\n", - "\n", - ":::{.callout-note .titlenormal}\n", - "\n", - "## Objekte, Funktionen, Methoden\n", - "\n", - "In klassischen objektorientierten Sprachen wie C++/Java haben Objekte üblicherweise mit ihnen assoziierte Funktionen, die Methoden des Objekts. \n", - "\n", - "In Julia gehören Methoden zu einer Funktion und nicht zu einem Objekt. \n", - "(Eine Ausnahme sind die Konstruktoren, also Funktionen, die genauso heißen wie ein Typ und ein Objekt dieses Typs erzeugen.) \n", - "\n", - "Sobald man einen neuen Typ definiert hat, kann man sowohl neue als auch bestehende Funktionen um neue Methoden für diesen Typ ergänzen.\n", - "\n", - " - Eine Funktion kann mehrfach für verschiedene Argumentlisten (Typ und Anzahl) definiert werden.\n", - " - Die Funktion hat dann mehrere Methoden.\n", - " - Beim Aufruf wird an Hand der konkreten Argumente entschieden, welche Methode genutzt wird *(multiple dispatch)*.\n", - " - Es ist typisch für Julia, dass für Standardfunktionen viele Methoden definiert sind. Diese können problemlos um weitere Methoden für eigene Typen erweitert werden. \n", - "\n", - ":::\n", - "\n", - "\n", - "Den Abstand zwischen zwei Punkten implementieren wir als Funktion mit zwei Methoden:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "2fcc529b", - "metadata": {}, - "outputs": [], - "source": [ - "function distance(p1::Point2D, p2::Point2D)\n", - " sqrt((p1.x-p2.x)^2 + (p1.y-p2.y)^2)\n", - "end\n", - "\n", - "function distance(p1::Point3D, p2::Point3D)\n", - " sqrt((p1.x-p2.x)^2 + (p1.y-p2.y)^2 + (p1.z-p2.z)^2)\n", - "end" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "aed12cee", - "metadata": {}, - "outputs": [], - "source": [ - "distance(p1, Point2D(2200, -300))" - ] - }, - { - "cell_type": "markdown", - "id": "796596b1", - "metadata": {}, - "source": [ - "Wie schon erwähnt, zeigt `methods()` die Methodentabelle einer Funktion an:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "e7472228", - "metadata": {}, - "outputs": [], - "source": [ - "methods(distance)" - ] - }, - { - "cell_type": "markdown", - "id": "e3d29877", - "metadata": {}, - "source": [ - "Das Macro `@which`, angewendet auf einen vollen Funktionsaufruf mmit konkreter Argumentliste, zeigt an, welche Methode zu diesen konkreten Argumenten ausgewählt wird:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "06ffd7b0", - "metadata": {}, - "outputs": [], - "source": [ - "@which sqrt(3.3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8019fcb5", - "metadata": {}, - "outputs": [], - "source": [ - "z = \"Hallo\" * '!'\n", - "println(z)\n", - "\n", - "@which \"Hallo\" * '!'" - ] - }, - { - "cell_type": "markdown", - "id": "f21cad4e", - "metadata": {}, - "source": [ - "Methoden können auch abstrakte Typen als Argument haben: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4cf39de0", - "metadata": {}, - "outputs": [], - "source": [ - "\"\"\"\n", - " Berechnet den Winkel ϕ (in Grad) der Polarkoordinaten (2D) bzw.\n", - " Kugelkoordinaten (3D) eines Punktes\n", - "\"\"\"\n", - "function phi_winkel(p::Point)\n", - " atand(p.y, p.x)\n", - "end\n", - "\n", - "phi_winkel(p1)" - ] - }, - { - "cell_type": "markdown", - "id": "c46f8247", - "metadata": {}, - "source": [ - ":::{.callout-tip collapse=\"true\"}\n", - "Ein in *triple quotes* eingeschlossene Text unmittelbat vor der Funktionsdefinition \n", - "wird automatisch in die Hilfe-Datenbank von Julia integriert:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "997f3797", - "metadata": {}, - "outputs": [], - "source": [ - "?phi_winkel" - ] - }, - { - "cell_type": "markdown", - "id": "f64e264a", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "\n", - "\n", - "Beim *multiple dispatch* wird die Methode angewendet, die unter allen passenden die spezifischste ist. Hier eine Funktion mit mehreren Methoden \n", - "(alle bis auf die letzte in der kurzen [*assignment form*](https://docs.julialang.org/en/v1/manual/functions/#man-functions) geschrieben):\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c0f3b3ee", - "metadata": {}, - "outputs": [], - "source": [ - "f(x::String, y::Number) = \"Args: String + Zahl\"\n", - "f(x::String, y::Int64) = \"Args: String + Int64\"\n", - "f(x::Number, y::Int64) = \"Args: Zahl + Int64\"\n", - "f(x::Int64, y:: Number) = \"Args: Int64 + Zahl\"\n", - "f(x::Number) = \"Arg: eine Zahl\"\n", - "\n", - "function f(x::Number, y::Number, z::String) \n", - " return \"Arg: 2 x Zahl + String\"\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "7c188a97", - "metadata": {}, - "source": [ - "Hier passen die ersten beiden Methoden. Gewählt wird die zweite, da sie spezifischer ist, `Int64 <: Number`. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "8f62a9c1", - "metadata": {}, - "outputs": [], - "source": [ - "f(\"Hallo\", 42)" - ] - }, - { - "cell_type": "markdown", - "id": "f15f9c8a", - "metadata": {}, - "source": [ - "Es kann sein, dass diese Vorschrift zu keinem eindeutigen Ergebnis führt, wenn man seine Methoden schlecht gewählt hat. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0b8c7b8d", - "metadata": {}, - "outputs": [], - "source": [ - "f(42, 42)" - ] - }, - { - "cell_type": "markdown", - "id": "81e6a8d2", - "metadata": {}, - "source": [ - "## Parametrisierte numerische Typen: `Rational` und `Complex`\n", - "\n", - "\n", - "- Für rationale Zahlen (Brüche) verwendet Julia `//` als Infix-Konstruktor:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "285efd4d", - "metadata": {}, - "outputs": [], - "source": [ - "@show Rational(23, 17) 4//16 + 1//3;" - ] - }, - { - "cell_type": "markdown", - "id": "fd1a9e04", - "metadata": {}, - "source": [ - "- Die imaginäre Einheit $\\sqrt{-1}$ heißt `im`\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "92f7c509", - "metadata": {}, - "outputs": [], - "source": [ - "@show Complex(0.4) 23 + 0.5im/(1-2im);" - ] - }, - { - "cell_type": "markdown", - "id": "12bd71e6", - "metadata": {}, - "source": [ - "`Rational` und `Complex` bestehen, ähnlich wie unser `Point2D`, aus 2 Feldern: Zähler und Nenner bzw. Real- und Imaginärteil.\n", - "\n", - "Der Typ dieser Felder ist allerdings nicht vollständig festgelegt. `Rational` und `Complex` sind _parametrisierte_ Typen.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "caa005d9", - "metadata": {}, - "outputs": [], - "source": [ - "x = 2//7 \n", - "@show typeof(x);" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d153b0e2", - "metadata": {}, - "outputs": [], - "source": [ - "y = BigInt(2)//7 \n", - "@show typeof(y) y^48;" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "ebcef28d", - "metadata": {}, - "outputs": [], - "source": [ - "x = 1 + 2im\n", - "typeof(x)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "512dfe32", - "metadata": {}, - "outputs": [], - "source": [ - "y = 1.0 + 2.0im\n", - "typeof(y)" - ] - }, - { - "cell_type": "markdown", - "id": "a5c41a3b", - "metadata": {}, - "source": [ - "Die konkreten Typen `Rational{Int64}`, `Rational{BigInt}`,..., `Complex{Int64}`, `Complex{Float64}}`, ... sind Subtypen von `Rational` bzw. `Complex`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "366b3941", - "metadata": {}, - "outputs": [], - "source": [ - "Rational{BigInt} <: Rational" - ] - }, - { - "cell_type": "markdown", - "id": "3bf8a72a", - "metadata": {}, - "source": [ - "Die Definitionen [sehen etwa so aus](https://github.com/JuliaLang/julia/blob/master/base/rational.jl#L6-L15):\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "15f36e48", - "metadata": {}, - "outputs": [], - "source": [ - "struct MyComplex{T<:Real} <: Number\n", - " re::T\n", - " im::T\n", - "end\n", - "\n", - "struct MyRational{T<:Integer} <: Real\n", - " num::T\n", - " den::T\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "e72521d9", - "metadata": {}, - "source": [ - "Die erste Definition besagt:\n", - "\n", - "- `MyComplex` hat zwei Felder `re` und `im`, beide vom gleichen Typ `T`. \n", - "- Dieser Typ `T` muss ein Untertyp von `Real` sein. \n", - "- `MyComplex` und alle seine Varianten wie `MyComplex{Float64}` sind Untertypen von `Number`. \n", - "\n", - "und die zweite besagt analog:\n", - "\n", - "- `MyRational` hat zwei Felder `num` und `den`, beide vom gleichen Typ `T`.\n", - "- Dieser Typ `T` muss ein Untertyp von `Integer` sein.\n", - "- `MyRational` und seine Varianten sind Untertypen von `Real`.\n", - "\n", - "Nun ist ℚ$\\subset$ ℝ, oder auf julianisch `Rational <: Real`. Also können die Komponenten einer komplexen Zahl auch rational sein: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "16d94216", - "metadata": {}, - "outputs": [], - "source": [ - "z = 3//4 + 5im\n", - "dump(z)" - ] - }, - { - "cell_type": "markdown", - "id": "716bc312", - "metadata": {}, - "source": [ - "Diese Strukturen sind ohne das `mutable`-Attribut definiert, also *immutable*:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "f9601b06", - "metadata": {}, - "outputs": [], - "source": [ - "x = 2.2 + 3.3im\n", - "println(\"Der Realteil ist: $(x.re)\")\n", - "\n", - "x.re = 4.4 " - ] - }, - { - "cell_type": "markdown", - "id": "5b0fe9d4", - "metadata": {}, - "source": [ - "Das ist so üblich. Wir betrachten das Objekt `9` vom Typ `Int64` ja auch als unveränderlich. \n", - "Das Folgende geht natürlich trotzdem:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d8d626b1", - "metadata": {}, - "outputs": [], - "source": [ - "x += 2.2" - ] - }, - { - "cell_type": "markdown", - "id": "49215683", - "metadata": {}, - "source": [ - "Hier wird ein neues Objekt vom Typ `Complex{Float64}` erzeugt und `x` zur Referenz auf dieses neue Objekt gemacht.\n", - "\n", - "Die Möglichkeiten des Typsystems verleiten leicht zum Spielen. Hier definieren wir eine `struct`, die wahlweise eine Maschinenzahl oder ein Paar von Ganzzahlen enthalten kann: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "99563913", - "metadata": {}, - "outputs": [], - "source": [ - "struct MyParms{T <: Union{Float64, Tuple{Int64, Int64}}}\n", - " param::T\n", - "end\n", - "\n", - "p1 = MyParms(33.3)\n", - "p2 = MyParms( (2, 4) )\n", - "\n", - "@show p1.param p2.param;" - ] - }, - { - "cell_type": "markdown", - "id": "32e74121", - "metadata": {}, - "source": [ - "## Typen als Objekte\n", - "\n", - "(1) Typen sind ebenfalls Objekte. Sie sind Objekte einer der drei \"Meta-Typen\" \n", - "\n", - " - `Union` (Union-Typen)\n", - " - `UnionAll` (parametrisierte Typen)\n", - " - `DataType` (alle konkreten und sonstige abstrakte Typen)\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "de573ecf", - "metadata": {}, - "outputs": [], - "source": [ - "@show 23779 isa Int64 Int64 isa DataType; " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "4123890d", - "metadata": {}, - "outputs": [], - "source": [ - "@show 2im isa Complex Complex isa UnionAll;" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "05a0390a", - "metadata": {}, - "outputs": [], - "source": [ - "@show 2im isa Complex{Int64} Complex{Int64} isa DataType;" - ] - }, - { - "cell_type": "markdown", - "id": "6537065b", - "metadata": {}, - "source": [ - "Diese 3 konkreten \"Meta-Typen\" sind übrigens Subtypen des abstrakten \"Meta-Typen\" `Type`.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "15a5484c", - "metadata": {}, - "outputs": [], - "source": [ - "subtypes(Type)" - ] - }, - { - "cell_type": "markdown", - "id": "6caefeac", - "metadata": {}, - "source": [ - "-----------------\n", - "\n", - "(2) Damit können Typen auch einfach Variablen zugewiesen werden: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "82d0e5fe", - "metadata": {}, - "outputs": [], - "source": [ - "x3 = Float64\n", - "@show x3(4) x3 <: Real x3==Float64 ; " - ] - }, - { - "cell_type": "markdown", - "id": "e2b3f283", - "metadata": {}, - "source": [ - ":::{.callout-note collapse=\"true\"}\n", - "\n", - "Dies zeigt auch, dass die [Style-Vorgaben in Julia](https://docs.julialang.org/en/v1/manual/style-guide/#Use-naming-conventions-consistent-with-Julia-base/) wie „Typen und Typvariablen starten mit Großbuchstaben, sonstige Variablen und Funktionen werden klein geschrieben.“ nur Konventionen sind und von der Sprache nicht erzwungen werden. \n", - "\n", - "Man sollte sie trotzdem einhalten, um den Code lesbar zu halten. \n", - "\n", - ":::\n", - "\n", - "\n", - "Wenn man solche Zuweisungen mit `const` für dauerhaft erklärt, entsteht ein \n", - " *type alias*.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9138ee10", - "metadata": {}, - "outputs": [], - "source": [ - "const MyCmplxF64 = MyComplex{Float64}\n", - "\n", - "z = MyComplex(1.1, 2.2)\n", - "typeof(z)" - ] - }, - { - "cell_type": "markdown", - "id": "4510cfbf", - "metadata": {}, - "source": [ - "--------\n", - "\n", - "(3) Typen können Argumente von Funktionen sein.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c1a0d9a2", - "metadata": {}, - "outputs": [], - "source": [ - "function myf(x, S, T)\n", - " if S <: T\n", - " println(\"$S is subtype of $T\")\n", - " end\n", - " return S(x)\n", - "end\n", - "\n", - "z = myf(43, UInt16, Real)\n", - "\n", - "@show z typeof(z);" - ] - }, - { - "cell_type": "markdown", - "id": "88fff457", - "metadata": {}, - "source": [ - "Wenn man diese Funktion mit Typsignaturen definieren möchte, kann man natürlich\n", - "```julia\n", - "function myf(x, S::Type, T::Type) ... end\n", - "```\n", - "schreiben. Üblicher ist hier die (dazu äquivalente) spezielle Syntax \n", - "```julia\n", - "function myf(x, ::Type{S}, ::Type{T}) where {S,T} ... end\n", - "```\n", - "bei der man in der `where`-Klausel auch noch Einschränkungen an die zulässigen Werte der Typvariablen `S` und `T` stellen kann.\n", - "\n", - "Wie definiere ich eine spezielle Methode von `myf`, die nur aufgerufen werden soll, wenn `S` und `T` gleich `Int64` sind? Das ist folgendermaßen möglich:\n", - "\n", - "```julia\n", - "function myf(x, ::Type{Int64}, ::Type{Int64}) ... end\n", - "```\n", - "`Type{Int64}` wirkt wie ein \"Meta-Typ\", dessen einzige Instanz der Typ `Int64` ist.\n", - "\n", - "\n", - "-----------------\n", - "\n", - "(4) Es gibt zahlreiche Operationen mit Typen als Argumenten. Wir haben schon `<:(T1, T2)`, `supertype(T)`, `supertypes(T)`, `subtypes(T)` gesehen. Erwähnt seien noch `typejoin(T1,T2)` (nächster gemeinsamer Vorfahre im Typbaum) und Tests wie `isconcretetype(T)`, `isabstracttype(T)`, `isstructtype(T)`. \n", - "\n", - "\n", - "\n", - "\n", - "## Invarianz parametrisierter Typen {#sec-invariance}\n", - "\n", - "Kann man in parametrisierten Typen auch nicht-konkrete Typen einsetzen? Gibt es `Complex{AbstractFloat}` oder `Complex{Union{Float32, Int16}}`? \n", - "\n", - "Ja, die gibt es; und es sind konkrete Typen, man kann also Objekte von diesem Typ erzeugen. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "96ebad91", - "metadata": {}, - "outputs": [], - "source": [ - "z5 = Complex{Integer}(2, 0x33)\n", - "dump(z5)" - ] - }, - { - "cell_type": "markdown", - "id": "9ad1639f", - "metadata": {}, - "source": [ - "Das ist eine heterogene Struktur. Jede Komponente hat einen individuellen Typ `T`, für den `T<:Integer` gilt. \n", - "\n", - "Nun gilt zwar\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "88a54bfb", - "metadata": {}, - "outputs": [], - "source": [ - "Int64 <: Integer" - ] - }, - { - "cell_type": "markdown", - "id": "1ba2b7d8", - "metadata": {}, - "source": [ - "aber es gilt nicht, dass \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c9b40433", - "metadata": {}, - "outputs": [], - "source": [ - "Complex{Int64} <: Complex{Integer}" - ] - }, - { - "cell_type": "markdown", - "id": "180d71a9", - "metadata": {}, - "source": [ - "Diese Typen sind beide konkret. Damit können sie in der Typhierarchie von Julia nicht in einer Sub/Supertype-Relation zueinander stehen. Julias parametrisierte Typen sind [in der Sprache der theoretischen Informatik](https://de.wikipedia.org/wiki/Kovarianz_und_Kontravarianz) **invariant**. \n", - "(Wenn aus `S<:T` folgen würde, dass auch `ParamType{S} <: ParamType{T}` gilt, würde man von **Kovarianz** sprechen.) \n", - "\n", - "\n", - "\n", - "## Generische Funktionen\n", - "\n", - "Der übliche (und in vielen Fällen empfohlene!) Programmierstil in Julia ist das Schreiben generischer Funktionen:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "81b5863d", - "metadata": {}, - "outputs": [], - "source": [ - "function fsinnfrei1(x, y)\n", - " return x * x * y\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "6c4c8113", - "metadata": {}, - "source": [ - "Diese Funktion funktioniert sofort mit allen Typen, für die die verwendeten Operationen definiert sind.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a29cc84e", - "metadata": {}, - "outputs": [], - "source": [ - "fsinnfrei1( Complex(2,3), 10), fsinnfrei1(\"Hallo\", '!')" - ] - }, - { - "cell_type": "markdown", - "id": "3351849c", - "metadata": {}, - "source": [ - "Man kann natürlich Typ-Annotationen benutzen, um die Verwendbarkeit einzuschränken oder um unterschiedliche Methoden für unterschiedliche Typen zu implementieren: \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "04a3d099", - "metadata": {}, - "outputs": [], - "source": [ - "function fsinnfrei2(x::Number, y::AbstractFloat)\n", - " return x * x * y\n", - "end\n", - "\n", - "function fsinnfrei2(x::String, y::String)\n", - " println(\"Sorry, I don't take strings!\")\n", - "end\n", - "\n", - "\n", - "@show fsinnfrei2(18, 2.0) fsinnfrei2(18, 2);" - ] - }, - { - "cell_type": "markdown", - "id": "178c8f0a", - "metadata": {}, - "source": [ - ":::{.callout-important}\n", - "\n", - "**Explizite Typannotationen sind fast immer irrelevent für die Geschwindigkeit des Codes!**\n", - "\n", - "Dies ist einer der wichtigsten *selling points* von Julia. \n", - "\n", - "Sobald eine Funktion zum ersten Mal mit bestimmten Typen aufgerufen wird, wird eine auf diese Argumenttypen spezialisierte Form der Funktion generiert und compiliert. Damit sind generische Funktionen in der Regel genauso schnell, wie die spezialisierten Funktionen, die man in anderen Sprachen schreibt. \n", - "\n", - "Generische Funktionen erlauben die Zusammenarbeit unterschiedlichster Pakete und eine hohe Abstraktion. \n", - "\n", - "Ein einfaches Beispiel: Das Paket `Measurements.jl` definiert einen neuen Datentyp `Measurement`, einen Wert mit Fehler, und die Arithmetik dieses Typs. Damit funktionieren generische Funktionen automatisch:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "95086dd4", - "metadata": {}, - "outputs": [], - "source": [ - "#| echo: false\n", - "#| output: false\n", - "\n", - "#= \n", - " -Measurements.jl/show.jl adds a method \n", - " Base.show(io::IO, ::MIME\"text/latex\", measure::Measurement)\n", - " - IJulia sends out a text/latex-cell in addition to the text/plain-cell \n", - " \n", - " \"outputs\": [\n", - " {\n", - " \"data\": {\n", - " \"text/latex\": [\n", - " \"$2590.0 \\\\pm 52.0$\"\n", - " ],\n", - " \"text/plain\": [\n", - " \"2590.0 ± 52.0\"\n", - " ]\n", - " },\n", - " whenever it finds this method, see\n", - " https://github.com/JuliaLang/IJulia.jl/commit/7311e517194ddba07af64952b0f9413401213050\n", - "\n", - " - Quarto takes this latex-cell in its qmd -> ipynb->exec->ipynb -> md pipeline, generating a :::{=tex} -div\n", - "\n", - " - so we delete the method\n", - "\n", - "=#\n", - "using Measurements\n", - "zz= @which Base.show(stdout, MIME\"text/latex\"(), 3±2)\n", - "Base.delete_method(zz)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "10bd90b2", - "metadata": {}, - "outputs": [], - "source": [ - "using Measurements\n", - "\n", - "x = 33.56±0.3\n", - "y = 2.3±0.02\n", - "\n", - "fsinnfrei1(x, y)" - ] - }, - { - "cell_type": "markdown", - "id": "1a1ebeb6", - "metadata": {}, - "source": [ - ":::\n", - "\n", - "## Typ-Parameter in Funktionsdefinitionen: die `where`-Klausel\n", - "\n", - "Wir wollen eine Funktion schreiben, die für **alle komplexen Integer** (und nur diese) funktioniert, z.B. eine [in ℤ[i] mögliche Primfaktorzerlegung](https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Zahl). Die Definition\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "c6c4920a", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "function isprime(x::Complex{Integer}) ... end" - ] - }, - { - "cell_type": "markdown", - "id": "ff815b70", - "metadata": {}, - "source": [ - "liefert nun nicht das Gewünschte, wie wir in @sec-invariance gesehen haben. Die Funktion würde für ein Argument vom Typ `Complex{Int64}` nicht funktionieren, da letzteres kein Subtyp von `Complex{Integer}` ist.\n", - "\n", - "Wir müssen eine Typ-Variable einführen. Dazu dient die `where`-Klausel.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "3c7d8952", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "function isprime(x::Complex{T}) where {T<:Integer}\n", - " ... \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "324c1a8e", - "metadata": {}, - "source": [ - "Das ist zu lesen als: \n", - "\n", - "> „Das Argument x soll von einem der Typen `Complex{T}` sein, wobei die Typvariable `T` irgendein Untertyp von `Integer` sein kann.“ \n", - "\n", - "Noch ein Beispiel:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "24e71b8d", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "function kgV(x::Complex{T}, y::Complex{S}) where {T<:Integer, S<:Integer}\n", - " ... \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "0b0e28c8", - "metadata": {}, - "source": [ - "> Die Argumente x und y können verschiedene Typen haben und beide müssen Subtypen von `Integer` sein.\n", - "\n", - "\n", - "Wenn es nur eine `where`-Klausel wie im vorletzten Beispiel gibt, kann man die geschweiften Klammern weglassen und \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "9886c460", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "function isprime(x::Complex{T}) where T<:Integer\n", - " ... \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "3e2c6355", - "metadata": {}, - "source": [ - "schreiben. Das lässt sich noch weiter kürzen zu\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "0d1e79dd", - "metadata": {}, - "outputs": [], - "source": [ - "#| eval: false\n", - "function isprime(x::Complex{<:Integer}) \n", - " ... \n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "d2b1739e", - "metadata": {}, - "source": [ - "Diese verschiedenen Varianten können verwirrend sein, aber das ist nur Syntax.\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "86265284", - "metadata": {}, - "outputs": [], - "source": [ - "C1 = Complex{T} where {T<:Integer} \n", - "C2 = Complex{T} where T<:Integer\n", - "C3 = Complex{<:Integer}\n", - "\n", - "C1 == C2 == C3" - ] - }, - { - "cell_type": "markdown", - "id": "e0eaebf1", - "metadata": {}, - "source": [ - "Kurze Syntax für einfache Fälle, ausführliche Syntax für komplexe Varianten.\n", - "\n", - "Als letztes sein bemerkt, dass `where T` die Kurzform von `where T<:Any` ist, also eine völlig unbeschränkte Typvariable einführt. Damit ist sowas möglich:\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "d5f32649", - "metadata": {}, - "outputs": [], - "source": [ - "function fgl(x::T, y::T) where T\n", - " println(\"Glückwunsch! x und y sind vom gleichen Typ!\")\n", - "end" - ] - }, - { - "cell_type": "markdown", - "id": "6b6732ba", - "metadata": {}, - "source": [ - "Diese Methode erfordert, dass die Argumente genau den gleichen, aber ansonsten beliebigen Typ haben. \n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "81785182", - "metadata": {}, - "outputs": [], - "source": [ - "fgl(33, 44)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "id": "a7688296", - "metadata": {}, - "outputs": [], - "source": [ - "fgl(33, 44.0)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Julia 1.10.2", - "language": "julia", - "name": "julia-1.10" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -}