Skip to content
Snippets Groups Projects
Commit 428f08b4 authored by Michele Nottoli's avatar Michele Nottoli
Browse files

Clean up of output from 1, implemented feedback from Rafael.

parent 042b6a19
Branches
No related tags found
No related merge requests found
%% Cell type:markdown id:7aad3586-d57e-4000-8688-aa5b53d48416 tags: %% Cell type:markdown id:7aad3586-d57e-4000-8688-aa5b53d48416 tags:
# Basics # Basics
%% Cell type:markdown id:aff6c2f6-3d10-412e-82aa-c199c98edbd7 tags: %% Cell type:markdown id:aff6c2f6-3d10-412e-82aa-c199c98edbd7 tags:
# Grundlagen # Grundlagen
%% Cell type:markdown id:bf904dbe-3197-4a91-bbb8-05e1c7f7dfee tags: %% Cell type:markdown id:bf904dbe-3197-4a91-bbb8-05e1c7f7dfee tags:
## Variables and elementary types ## Variables and elementary types
Defining variables in Julia works like in most languages: Defining variables in Julia works like in most languages:
%% Cell type:markdown id:3be02b91-9619-4cfd-b463-2add42babbcc tags: %% Cell type:markdown id:3be02b91-9619-4cfd-b463-2add42babbcc tags:
## Variablen und elementare Datentypen ## Variablen und elementare Datentypen
Das Definieren von Variablen in Julia funktioniert wie in den meisten Sprachen: Das Definieren von Variablen in Julia funktioniert wie in den meisten Sprachen:
%% Cell type:code id:3c44023b-06c9-4420-9af3-da2ec37b02da tags: %% Cell type:code id:3c44023b-06c9-4420-9af3-da2ec37b02da tags:
``` julia ``` julia
int = 4 # An integer int = 4 # An integer
``` ```
%% Cell type:code id:b2f9ba27-bf65-40d8-b0ac-e3d86c99dd40 tags: %% Cell type:code id:b2f9ba27-bf65-40d8-b0ac-e3d86c99dd40 tags:
``` julia ``` julia
str = "Hi" # A string str = "Hi" # A string
``` ```
%% Cell type:code id:87a83355-5088-47d3-b698-2c6902aaa6a0 tags: %% Cell type:code id:87a83355-5088-47d3-b698-2c6902aaa6a0 tags:
``` julia ``` julia
float = 1.2 # A floating-point number float = 1.2 # A floating-point number
``` ```
%% Cell type:code id:597523f1-4041-4fc6-9be2-2c94a93fd633 tags: %% Cell type:code id:597523f1-4041-4fc6-9be2-2c94a93fd633 tags:
``` julia ``` julia
bool = true # A boolean (also false) bool = true # A boolean (also false)
``` ```
%% Cell type:markdown id:0c538bdb-f995-4589-bee7-0989c922090c tags: %% Cell type:markdown id:0c538bdb-f995-4589-bee7-0989c922090c tags:
The type is automatically inferred: The type is automatically inferred:
%% Cell type:markdown id:816bc593-70cc-4e0f-b461-c9022d9587f6 tags: %% Cell type:markdown id:816bc593-70cc-4e0f-b461-c9022d9587f6 tags:
Der Typ wird automatisch abgeleitet: Der Typ wird automatisch abgeleitet:
%% Cell type:code id:b80c6777-3dea-4f45-98b3-0a3eee196183 tags: %% Cell type:code id:b80c6777-3dea-4f45-98b3-0a3eee196183 tags:
``` julia ``` julia
typeof(int) typeof(int)
``` ```
%% Cell type:code id:1fb6cbd2-871f-40a4-ae84-e7ee46e75a61 tags: %% Cell type:code id:1fb6cbd2-871f-40a4-ae84-e7ee46e75a61 tags:
``` julia ``` julia
typeof(str) typeof(str)
``` ```
%% Cell type:code id:a16a6f08-f19a-42e0-baac-aaa88ebba1af tags: %% Cell type:code id:a16a6f08-f19a-42e0-baac-aaa88ebba1af tags:
``` julia ``` julia
typeof(float) typeof(float)
``` ```
%% Cell type:markdown id:09d035eb-22aa-49f5-9fd1-a5b16973f386 tags: %% Cell type:markdown id:09d035eb-22aa-49f5-9fd1-a5b16973f386 tags:
Julia supports a large range of integer and floating-point types out of the box, for example: Julia supports a large range of integer and floating-point types out of the box, for example:
%% Cell type:markdown id:d5e586cc-874a-46d5-9c7c-d1136d73492e tags: %% Cell type:markdown id:d5e586cc-874a-46d5-9c7c-d1136d73492e tags:
Julia unterstützt von Haus aus eine große Bandbreite von Ganzzahl- und Gleitkommazahlentypen, zum Beispiel: Julia unterstützt von Haus aus eine große Bandbreite von Ganzzahl- und Gleitkommazahlentypen, zum Beispiel:
%% Cell type:code id:88f24b01-f4a5-4030-af2c-a5d30223d047 tags: %% Cell type:code id:88f24b01-f4a5-4030-af2c-a5d30223d047 tags:
``` julia ``` julia
x = UInt8(1) # 8-bit wide unsigned integer x = UInt8(1) # 8-bit wide unsigned integer
y = Int32(-1) # 32-bit wide signed integer y = Int32(-1) # 32-bit wide signed integer
z = Float32(0.2) # single precision z = Float32(0.2) # single precision
α = Float16(-1.0) # half precision α = Float16(-1.0) # half precision
β = ComplexF64(2. + 8im) # Complex number (composed of two Float64) β = ComplexF64(2. + 8im) # Complex number (composed of two Float64)
``` ```
%% Cell type:markdown id:a615bbc0-732e-461f-8c4c-a972fa2be731 tags: %% Cell type:markdown id:a615bbc0-732e-461f-8c4c-a972fa2be731 tags:
If you give a variable an illegal name, you get a syntax error: If you give a variable an illegal name, you get a syntax error:
%% Cell type:markdown id:bf9f6efc-6b47-415c-8504-35a2b1a80f18 tags: %% Cell type:markdown id:bf9f6efc-6b47-415c-8504-35a2b1a80f18 tags:
Wenn Sie einer Variable einen ungültigen Namen geben, erhalten Sie einen Syntaxfehler: Wenn Sie einer Variable einen ungültigen Namen geben, erhalten Sie einen Syntaxfehler:
%% Cell type:code id:1ca20515-6d66-40c3-84f1-2e24ece096cd tags: %% Cell type:code id:1ca20515-6d66-40c3-84f1-2e24ece096cd tags:
``` julia ``` julia
1test = "hello" 1test = "hello"
``` ```
%% Cell type:code id:2c61f59e-2c2f-4049-8624-35e0712b2cf1 tags: %% Cell type:code id:2c61f59e-2c2f-4049-8624-35e0712b2cf1 tags:
``` julia ``` julia
more@ = 1000000 more@ = 1000000
``` ```
%% Cell type:code id:85040b19-b0a9-4baa-8748-5ea62f8b5633 tags: %% Cell type:code id:85040b19-b0a9-4baa-8748-5ea62f8b5633 tags:
``` julia ``` julia
struct = "another illegale variable name" struct = "another illegale variable name"
``` ```
%% Cell type:markdown id:cc36688b-c983-43f8-8bdf-9b82aae59909 tags: %% Cell type:markdown id:cc36688b-c983-43f8-8bdf-9b82aae59909 tags:
It turns out that `struct` is one of Julia’s keywords, and they cannot be used as variable names. It turns out that `struct` is one of Julia’s keywords, and they cannot be used as variable names.
- For more Julia's keywords, see [https://docs.julialang.org/en/v1/base/base/#Keywords](https://docs.julialang.org/en/v1/base/base/#Keywords). - For more Julia's keywords, see [https://docs.julialang.org/en/v1/base/base/#Keywords](https://docs.julialang.org/en/v1/base/base/#Keywords).
- For more details on `Variable`, see [https://docs.julialang.org/en/v1/manual/variables/](https://docs.julialang.org/en/v1/manual/variables/). - For more details on `Variable`, see [https://docs.julialang.org/en/v1/manual/variables/](https://docs.julialang.org/en/v1/manual/variables/).
%% Cell type:markdown id:2e5659b9-9e66-448a-a768-23d7085d7dac tags: %% Cell type:markdown id:2e5659b9-9e66-448a-a768-23d7085d7dac tags:
Es stellt sich heraus, dass `struct` eines der Schlüsselwörter von Julia ist und nicht als Variablennamen verwendet werden kann. Es stellt sich heraus, dass `struct` eines der Schlüsselwörter von Julia ist und nicht als Variablennamen verwendet werden kann.
- Für weitere Schlüsselwörter von Julia, siehe [https://docs.julialang.org/en/v1/base/base/#Keywords](https://docs.julialang.org/en/v1/base/base/#Keywords). - Für weitere Schlüsselwörter von Julia, siehe [https://docs.julialang.org/en/v1/base/base/#Keywords](https://docs.julialang.org/en/v1/base/base/#Keywords).
- Für weitere Details über `Variabeln`, siehe [https://docs.julialang.org/en/v1/manual/variables/](https://docs.julialang.org/en/v1/manual/variables/). - Für weitere Details über `Variabeln`, siehe [https://docs.julialang.org/en/v1/manual/variables/](https://docs.julialang.org/en/v1/manual/variables/).
%% Cell type:markdown id:de111dbe-f7ed-4e1a-8ec0-c5e65bd63bbf tags: %% Cell type:markdown id:de111dbe-f7ed-4e1a-8ec0-c5e65bd63bbf tags:
### Strings ### Strings
%% Cell type:markdown id:e099c88a-5848-4730-be7d-b7651bc3db29 tags: %% Cell type:markdown id:e099c88a-5848-4730-be7d-b7651bc3db29 tags:
### Zeichenketten ### Zeichenketten
%% Cell type:markdown id:1b3531e9-33db-4c51-b394-c1def6621519 tags: %% Cell type:markdown id:1b3531e9-33db-4c51-b394-c1def6621519 tags:
In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal: In general, you can’t perform mathematical operations on strings, even if the strings look like numbers, so the following are illegal:
%% Cell type:markdown id:925cbca6-cce3-4084-96a2-fe0a5acdb1e9 tags: %% Cell type:markdown id:925cbca6-cce3-4084-96a2-fe0a5acdb1e9 tags:
Im Allgemeinen können Sie mathematische Operationen nicht auf Zeichenketten ausführen, auch wenn die Zeichenketten wie Zahlen aussehen. Daher sind die folgenden Operationen nicht erlaubt: Im Allgemeinen können Sie mathematische Operationen nicht auf Zeichenketten ausführen, auch wenn die Zeichenketten wie Zahlen aussehen. Daher sind die folgenden Operationen nicht erlaubt:
%% Cell type:code id:246f1db8-d734-413d-9237-b2434e071914 tags: %% Cell type:code id:246f1db8-d734-413d-9237-b2434e071914 tags:
``` julia ``` julia
"2" - "1" "2" - "1"
"eggs" / "easy" "eggs" / "easy"
"third" + "a charm" "third" + "a charm"
``` ```
%% Cell type:markdown id:c94f1187-67f8-473e-910c-2eb145ed59dd tags: %% Cell type:markdown id:c94f1187-67f8-473e-910c-2eb145ed59dd tags:
But there are two exceptions, * and ^. But there are two exceptions, * and ^.
%% Cell type:markdown id:c2c39aa8-d98b-42dd-8e7c-09463f78d22c tags: %% Cell type:markdown id:c2c39aa8-d98b-42dd-8e7c-09463f78d22c tags:
Es gibt jedoch zwei Ausnahmen, * und ^. Es gibt jedoch zwei Ausnahmen, * und ^.
%% Cell type:code id:b3a0f6e1-e28b-4fb7-baa3-bb003de3dc24 tags: %% Cell type:code id:b3a0f6e1-e28b-4fb7-baa3-bb003de3dc24 tags:
``` julia ``` julia
"Hello " * "world" "Hello " * "world"
``` ```
%% Cell type:code id:0c963c3c-47c7-4805-8be6-621b72fdb62e tags: %% Cell type:code id:0c963c3c-47c7-4805-8be6-621b72fdb62e tags:
``` julia ``` julia
"hello! "^5 "hello! "^5
``` ```
%% Cell type:markdown id:362f9d04-eff9-4594-aa22-a9c8d601fb1e tags: %% Cell type:markdown id:362f9d04-eff9-4594-aa22-a9c8d601fb1e tags:
For more details: [https://docs.julialang.org/en/v1/manual/strings/](https://docs.julialang.org/en/v1/manual/strings/). For more details: [https://docs.julialang.org/en/v1/manual/strings/](https://docs.julialang.org/en/v1/manual/strings/).
%% Cell type:markdown id:7b7ff4e3 tags: %% Cell type:markdown id:7b7ff4e3 tags:
Für weitere Details: [https://docs.julialang.org/en/v1/manual/strings/](https://docs.julialang.org/en/v1/manual/strings/). Für weitere Details: [https://docs.julialang.org/en/v1/manual/strings/](https://docs.julialang.org/en/v1/manual/strings/).
%% Cell type:markdown id:61ff8194-669c-4ece-ba31-44e88ed808ac tags: %% Cell type:markdown id:61ff8194-669c-4ece-ba31-44e88ed808ac tags:
### Exercises ### Exercises
%% Cell type:markdown id:43fe0add-b90d-4ed4-862e-37a4361d2354 tags: %% Cell type:markdown id:43fe0add-b90d-4ed4-862e-37a4361d2354 tags:
### Übungen ### Übungen
%% Cell type:markdown id:e0aecc9c-e77f-449e-8aff-e1ffcf5d7833 tags: %% Cell type:markdown id:e0aecc9c-e77f-449e-8aff-e1ffcf5d7833 tags:
Practice using Julia as a calculator: Practice using Julia as a calculator:
- The volume of a sphere with radius r is 4/3πr^3. What is the volume of a sphere with radius 5? - The volume of a sphere with radius r is 4/3πr^3. What is the volume of a sphere with radius 5?
%% Cell type:markdown id:3e392c67-df83-49fc-831d-12e157e4a85c tags: %% Cell type:markdown id:3e392c67-df83-49fc-831d-12e157e4a85c tags:
Üben Sie, Julia als Taschenrechner zu verwenden: Üben Sie, Julia als Taschenrechner zu verwenden:
- Die Formel für das Volumen einer Kugel mit Radius r lautet 4/3πr^3. Was ist das Volumen einer Kugel mit Radius 5? - Die Formel für das Volumen einer Kugel mit Radius r lautet 4/3πr^3. Was ist das Volumen einer Kugel mit Radius 5?
%% Cell type:code id:fc538246-418c-4ebe-b487-81feba4383c8 tags: %% Cell type:code id:fc538246-418c-4ebe-b487-81feba4383c8 tags:
``` julia ``` julia
4*pi*5^3/3 4*pi*5^3/3
``` ```
%% Cell type:markdown id:10f1604d-8e81-4f96-8b6f-95753f0b5c4f tags: %% Cell type:markdown id:10f1604d-8e81-4f96-8b6f-95753f0b5c4f tags:
- Suppose the cover price of a book is € 24.95, but bookstores get a 40 % discount. Shipping costs € 3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies? - Suppose the cover price of a book is € 24.95, but bookstores get a 40 % discount. Shipping costs € 3 for the first copy and 75 cents for each additional copy. What is the total wholesale cost for 60 copies?
%% Cell type:markdown id:32f7a6f1-6a19-4ebe-bd1b-846f861dc721 tags: %% Cell type:markdown id:32f7a6f1-6a19-4ebe-bd1b-846f861dc721 tags:
- Angenommen, der Listenpreis eines Buches beträgt € 24,95, aber Buchhandlungen erhalten einen Rabatt von 40 %. Der Versand kostet € 3 für das erste Exemplar und 75 Cent für jedes zusätzliche Exemplar. Was sind die gesamten Großhandelskosten für 60 Exemplare? - Angenommen, der Listenpreis eines Buches beträgt € 24,95, aber Buchhandlungen erhalten einen Rabatt von 40 %. Der Versand kostet € 3 für das erste Exemplar und 75 Cent für jedes zusätzliche Exemplar. Was sind die gesamten Großhandelskosten für 60 Exemplare?
%% Cell type:code id:bd4150cf-005a-4087-aa92-5f4b18e4d197 tags: %% Cell type:code id:bd4150cf-005a-4087-aa92-5f4b18e4d197 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:dc9cddb9-717d-4ba0-b478-beb00afc46c8 tags: %% Cell type:markdown id:dc9cddb9-717d-4ba0-b478-beb00afc46c8 tags:
## Conditionals and Boolean Expressions ## Conditionals and Boolean Expressions
A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces true if they are equal and false otherwise: A boolean expression is an expression that is either true or false. The following examples use the operator ==, which compares two operands and produces true if they are equal and false otherwise:
%% Cell type:markdown id:53e26ee8-c10d-42e4-bbb9-cb5f696139ba tags: %% Cell type:markdown id:53e26ee8-c10d-42e4-bbb9-cb5f696139ba tags:
## Bedingungen und boolesche Ausdrücke ## Bedingungen und boolesche Ausdrücke
Ein boolescher Ausdruck ist ein Ausdruck, der entweder wahr oder falsch ist. Die folgenden Beispiele verwenden den Operator ==, der zwei Operanden vergleicht und true zurückgibt, wenn sie gleich sind, andernfalls false: Ein boolescher Ausdruck ist ein Ausdruck, der entweder wahr oder falsch ist. Die folgenden Beispiele verwenden den Operator ==, der zwei Operanden vergleicht und true zurückgibt, wenn sie gleich sind, andernfalls false:
%% Cell type:code id:7de4ffe9-4730-47dd-b074-1525bf9937b1 tags: %% Cell type:code id:7de4ffe9-4730-47dd-b074-1525bf9937b1 tags:
``` julia ``` julia
5 == 5 5 == 5
``` ```
%% Cell type:code id:c02939dd-6f25-4916-8394-a5f95d0200df tags: %% Cell type:code id:c02939dd-6f25-4916-8394-a5f95d0200df tags:
``` julia ``` julia
5 == 6 5 == 6
``` ```
%% Cell type:markdown id:9a108e63-7d58-489d-b7ef-49629c879d29 tags: %% Cell type:markdown id:9a108e63-7d58-489d-b7ef-49629c879d29 tags:
The == operator is one of the relational operators; the others are: The == operator is one of the relational operators; the others are:
%% Cell type:markdown id:4722b7b7-3f80-454f-bd8b-f67912105f79 tags: %% Cell type:markdown id:4722b7b7-3f80-454f-bd8b-f67912105f79 tags:
Der == Operator ist einer der relationalen Operatoren; die anderen sind: Der == Operator ist einer der relationalen Operatoren; die anderen sind:
%% Cell type:code id:b59cd314-fd03-4609-ac1b-7329a2c3cc38 tags: %% Cell type:code id:b59cd314-fd03-4609-ac1b-7329a2c3cc38 tags:
``` julia ``` julia
x = 3; y = 4 x = 3; y = 4
x != y # x is not equal to y x != y # x is not equal to y
x ≠ y # (to get the ≠ symbol, type \ne and then press TAB) x ≠ y # (to get the ≠ symbol, type \ne and then press TAB)
x > y # x is greater than y x > y # x is greater than y
x < y # x is less than y x < y # x is less than y
x >= y # x is greater than or equal to y x >= y # x is greater than or equal to y
x ≥ y # (to get the ≥ symbol, type \ge and then press TAB) x ≥ y # (to get the ≥ symbol, type \ge and then press TAB)
x <= y # x is less than or equal to y x <= y # x is less than or equal to y
x ≤ y # (to get the ≤ symbol, type \le and then press TAB) x ≤ y # (to get the ≤ symbol, type \le and then press TAB)
``` ```
%% Cell type:markdown id:15e20f55-1a43-4d0d-94bc-d2de0ee2fe8c tags: %% Cell type:markdown id:15e20f55-1a43-4d0d-94bc-d2de0ee2fe8c tags:
There are three logical operators: && (and), || (or), and ! (not). The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 && x < 10 is true only if x is greater than 0 and less than 10. There are three logical operators: && (and), || (or), and ! (not). The semantics (meaning) of these operators is similar to their meaning in English. For example, x > 0 && x < 10 is true only if x is greater than 0 and less than 10.
%% Cell type:markdown id:01c9f186-294f-4659-bc32-cee3b6ff4f40 tags: %% Cell type:markdown id:01c9f186-294f-4659-bc32-cee3b6ff4f40 tags:
Es gibt drei logische Operatoren: && (und), || (oder) und ! (nicht). Die Bedeutung dieser Operatoren entspricht weitgehend ihrer Bedeutung im Englischen. Zum Beispiel ist x > 0 && x < 10 nur dann wahr, wenn x größer als 0 und kleiner als 10 ist. Es gibt drei logische Operatoren: && (und), || (oder) und ! (nicht). Die Bedeutung dieser Operatoren entspricht weitgehend ihrer Bedeutung im Englischen. Zum Beispiel ist x > 0 && x < 10 nur dann wahr, wenn x größer als 0 und kleiner als 10 ist.
%% Cell type:code id:d1e6e2ce-bb0c-4776-80b6-22ceb9c68397 tags: %% Cell type:code id:d1e6e2ce-bb0c-4776-80b6-22ceb9c68397 tags:
``` julia ``` julia
x = 4 x = 4
x > 0 && x < 10 x > 0 && x < 10
``` ```
%% Cell type:markdown id:da591654-6360-4f56-956b-07493d1d2247 tags: %% Cell type:markdown id:da591654-6360-4f56-956b-07493d1d2247 tags:
It is also worth mentioning that in combined logical expression not all conditions are necessarily executed. It is also worth mentioning that in combined logical expression not all conditions are necessarily executed.
%% Cell type:markdown id:857cde91-3430-480c-9f24-bb9c465248d9 tags: %% Cell type:markdown id:857cde91-3430-480c-9f24-bb9c465248d9 tags:
Es ist auch erwähnenswert, dass bei kombinierten logischen Ausdrücken nicht alle Bedingungen notwendigerweise ausgeführt werden. Es ist auch erwähnenswert, dass bei kombinierten logischen Ausdrücken nicht alle Bedingungen notwendigerweise ausgeführt werden.
%% Cell type:code id:e92abf7b-5414-4aee-abaf-a4e52b1c06d3 tags: %% Cell type:code id:e92abf7b-5414-4aee-abaf-a4e52b1c06d3 tags:
``` julia ``` julia
true || println("The RHS of || is only run") true || println("The RHS of || is only run")
false || println("if the LHS is false") false || println("if the LHS is false")
``` ```
%% Cell type:code id:c8a9d8ac-5378-4ebb-810b-9ae3194d670c tags: %% Cell type:code id:c8a9d8ac-5378-4ebb-810b-9ae3194d670c tags:
``` julia ``` julia
iseven(3) && println("The RHS of || is only run") iseven(3) && println("The RHS of || is only run")
isodd(3) && println("if the LHS is true") isodd(3) && println("if the LHS is true")
``` ```
%% Cell type:markdown id:be0c63e0-35a9-43c7-9b30-d04072ee6904 tags: %% Cell type:markdown id:be0c63e0-35a9-43c7-9b30-d04072ee6904 tags:
Finally, the ! operator negates a boolean expression, so !(x > y) is true if x > y is false, that is, if x is less than or equal to y. Finally, the ! operator negates a boolean expression, so !(x > y) is true if x > y is false, that is, if x is less than or equal to y.
%% Cell type:markdown id:d8db49a8-6c6c-4abf-9a5b-5d27765ab1c7 tags: %% Cell type:markdown id:d8db49a8-6c6c-4abf-9a5b-5d27765ab1c7 tags:
Schließlich kehrt der ! Operator einen booleschen Ausdruck um, sodass !(x > y) wahr ist, wenn x > y falsch ist, das heißt, wenn x kleiner oder gleich y ist. Schließlich kehrt der ! Operator einen booleschen Ausdruck um, sodass !(x > y) wahr ist, wenn x > y falsch ist, das heißt, wenn x kleiner oder gleich y ist.
%% Cell type:code id:e43ab736-03e2-4040-a15e-48305037ba23 tags: %% Cell type:code id:e43ab736-03e2-4040-a15e-48305037ba23 tags:
``` julia ``` julia
x = 4 x = 4
!(x > 0 && x < 10) !(x > 0 && x < 10)
``` ```
%% Cell type:markdown id:7064ae20-6d63-40fc-85c5-080ace54e7b6 tags: %% Cell type:markdown id:7064ae20-6d63-40fc-85c5-080ace54e7b6 tags:
Unsurprisingly Julia has the standard conditionals. Unsurprisingly Julia has the standard conditionals.
%% Cell type:markdown id:fbe0d04d-29c9-4bd0-9cfb-0c57a3b3f877 tags: %% Cell type:markdown id:fbe0d04d-29c9-4bd0-9cfb-0c57a3b3f877 tags:
Es überrascht nicht, dass Julia die üblichen Bedingungsanweisungen hat. Es überrascht nicht, dass Julia die üblichen Bedingungsanweisungen hat.
%% Cell type:code id:4f140e2c-a240-496d-904c-c60778397bcf tags: %% Cell type:code id:4f140e2c-a240-496d-904c-c60778397bcf tags:
``` julia ``` julia
x = 3; y = 2 x = 3; y = 2
if x < y if x < y
println("x is less than y") println("x is less than y")
elseif x > y elseif x > y
println("x is greater than y") println("x is greater than y")
else else
println("x is equal to y") println("x is equal to y")
end end
``` ```
%% Cell type:markdown id:4c57139e-da0c-48ef-a86f-4de80e1d7ca4 tags: %% Cell type:markdown id:4c57139e-da0c-48ef-a86f-4de80e1d7ca4 tags:
There is also an inline conditional. There is also an inline conditional.
%% Cell type:markdown id:64a3bf26-156f-40a8-8d8c-d4b2f838ef95 tags: %% Cell type:markdown id:64a3bf26-156f-40a8-8d8c-d4b2f838ef95 tags:
Es gibt auch eine bedingte Inline-Anweisung. Es gibt auch eine bedingte Inline-Anweisung.
%% Cell type:code id:9d0801fd-b0d3-41e0-8b54-19a6b4539231 tags: %% Cell type:code id:9d0801fd-b0d3-41e0-8b54-19a6b4539231 tags:
``` julia ``` julia
x = 6 x = 6
x < 5 ? "smaller than 5" : "larger or equal 5" x < 5 ? "smaller than 5" : "larger or equal 5"
``` ```
%% Cell type:markdown id:b597c363-8066-470e-b1c8-edd00b114317 tags: %% Cell type:markdown id:b597c363-8066-470e-b1c8-edd00b114317 tags:
For more details: [https://docs.julialang.org/en/v1/manual/control-flow/](https://docs.julialang.org/en/v1/manual/control-flow/). For more details: [https://docs.julialang.org/en/v1/manual/control-flow/](https://docs.julialang.org/en/v1/manual/control-flow/).
%% Cell type:markdown id:2539a6ec-e950-4b76-ad13-4ac9bb28ec26 tags: %% Cell type:markdown id:2539a6ec-e950-4b76-ad13-4ac9bb28ec26 tags:
Für weitere Details siehe: [https://docs.julialang.org/en/v1/manual/control-flow/](https://docs.julialang.org/en/v1/manual/control-flow/) Für weitere Details siehe: [https://docs.julialang.org/en/v1/manual/control-flow/](https://docs.julialang.org/en/v1/manual/control-flow/)
%% Cell type:markdown id:e4510840-0890-4217-8a8c-c24aa5d3405b tags: %% Cell type:markdown id:e4510840-0890-4217-8a8c-c24aa5d3405b tags:
## Iterations ## Iterations
Julia implements the standard `for` and `while` constructs. Julia implements the standard `for` and `while` constructs.
%% Cell type:markdown id:7c8eb301-3404-4d13-bc5d-f4e2f71cfa12 tags: %% Cell type:markdown id:7c8eb301-3404-4d13-bc5d-f4e2f71cfa12 tags:
## Iterationen ## Iterationen
Julia implementiert die üblichen `for`- und `while`-Befehle. Julia implementiert die üblichen `for`- und `while`-Befehle.
%% Cell type:code id:9632f210-c713-4829-8187-cf5554adad87 tags: %% Cell type:code id:9632f210-c713-4829-8187-cf5554adad87 tags:
``` julia ``` julia
for i in 1:5 for i in 1:5
println("Hello from number $i") println("Hello from number $i")
end end
``` ```
%% Cell type:markdown id:f00caf15-4992-4c0a-8324-9d2be966346d tags: %% Cell type:markdown id:f00caf15-4992-4c0a-8324-9d2be966346d tags:
Where the `1:5` is a `Range`-object, but it could be any iterable. There are a few syntax variations, including: Where the `1:5` is a `Range`-object, but it could be any iterable. There are a few syntax variations, including:
%% Cell type:markdown id:d0933cf7-b409-4c40-8184-70d0770a06b1 tags: %% Cell type:markdown id:d0933cf7-b409-4c40-8184-70d0770a06b1 tags:
Dabei ist `1:5` ein `Range`-Objekt, aber es könnte jede Art von iterierbarem Objekt sein. Es gibt einige syntaktische Variationen, einschließlich: Dabei ist `1:5` ein `Range`-Objekt, aber es könnte jede Art von iterierbarem Objekt sein. Es gibt einige syntaktische Variationen, einschließlich:
%% Cell type:code id:70a9f620-e4ce-4367-b0f5-de37db3f48b5 tags: %% Cell type:code id:70a9f620-e4ce-4367-b0f5-de37db3f48b5 tags:
``` julia ``` julia
result = 0 result = 0
# To get ∈ write \in and then press TAB # To get ∈ write \in and then press TAB
for j ∈ 1:0.5:3 # Note the step parameter for j ∈ 1:0.5:3 # Note the step parameter
result += j result += j
end end
println(result) println(result)
``` ```
%% Cell type:code id:e83b2d88-b0f2-43f1-9187-65fbc75f0d3b tags: %% Cell type:code id:e83b2d88-b0f2-43f1-9187-65fbc75f0d3b tags:
``` julia ``` julia
n = 10 n = 10
while n > 0 while n > 0
print(n, " ") print(n, " ")
n = n - 1 n = n - 1
end end
``` ```
%% Cell type:markdown id:f19d5051-ce82-49cc-80aa-2434a6adc9d0 tags: %% Cell type:markdown id:f19d5051-ce82-49cc-80aa-2434a6adc9d0 tags:
The loops can be further controlled with the `break` and `continue` keywords. The loops can be further controlled with the `break` and `continue` keywords.
%% Cell type:markdown id:76563c39-4e45-4daf-b703-575909f70787 tags: %% Cell type:markdown id:76563c39-4e45-4daf-b703-575909f70787 tags:
Die Schleifen können mit den Schlüsselwörtern `break` und `continue` weiter gesteuert werden. Die Schleifen können mit den Schlüsselwörtern `break` und `continue` weiter gesteuert werden.
%% Cell type:markdown id:d0ebce97-3054-4eba-821d-92f27793d752 tags: %% Cell type:markdown id:d0ebce97-3054-4eba-821d-92f27793d752 tags:
Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can use the `break` statement to jump out of the loop. Sometimes you don’t know it’s time to end a loop until you get half way through the body. In that case you can use the `break` statement to jump out of the loop.
%% Cell type:markdown id:b38f525d-db83-4fbf-808c-bf39080650f5 tags: %% Cell type:markdown id:b38f525d-db83-4fbf-808c-bf39080650f5 tags:
Manchmal weiß man nicht, wann es an der Zeit ist, eine Schleife zu beenden, bis man sich bereits in der Mitte des Schleifenkörpers befindet. In diesem Fall können Sie das `break`-Statement verwenden, um aus der Schleife auszubrechen. Manchmal weiß man nicht, wann es an der Zeit ist, eine Schleife zu beenden, bis man sich bereits in der Mitte des Schleifenkörpers befindet. In diesem Fall können Sie das `break`-Statement verwenden, um aus der Schleife auszubrechen.
%% Cell type:code id:9bb642e3-e3b1-488d-939f-6932feb62479 tags: %% Cell type:code id:9bb642e3-e3b1-488d-939f-6932feb62479 tags:
``` julia ``` julia
while true while true
print("> ") print("> ")
line = readline() line = readline()
if line == "done" if line == "done"
break break
end end
println(line) println(line)
end end
println("Done!") println("Done!")
``` ```
%% Cell type:markdown id:98eee547-21fe-4022-bde5-b02ababa26dd tags: %% Cell type:markdown id:98eee547-21fe-4022-bde5-b02ababa26dd tags:
The `break` statement exits the loop. When a `continue` statement is encountered inside a loop, control jumps to the beginning of the loop for the next iteration, skipping the execution of statements inside the body of the loop for the current iteration. For example: The `break` statement exits the loop. When a `continue` statement is encountered inside a loop, control jumps to the beginning of the loop for the next iteration, skipping the execution of statements inside the body of the loop for the current iteration. For example:
%% Cell type:markdown id:873c3625-3b99-48e5-9821-9b696a8f8a12 tags: %% Cell type:markdown id:873c3625-3b99-48e5-9821-9b696a8f8a12 tags:
Das `break`-Statement beendet die Schleife. Wenn ein `continue`-Statement in einer Schleife auftritt, springt die Kontrolle zum Anfang der Schleife für die nächste Iteration, wobei die Ausführung der Anweisungen im Innern der Schleife für die aktuelle Iteration übersprungen wird. Zum Beispiel: Das `break`-Statement beendet die Schleife. Wenn ein `continue`-Statement in einer Schleife auftritt, springt die Kontrolle zum Anfang der Schleife für die nächste Iteration, wobei die Ausführung der Anweisungen im Innern der Schleife für die aktuelle Iteration übersprungen wird. Zum Beispiel:
%% Cell type:code id:7f1c2595-8836-4308-9769-f4140d402582 tags: %% Cell type:code id:7f1c2595-8836-4308-9769-f4140d402582 tags:
``` julia ``` julia
for i in 1:10 for i in 1:10
if i % 3 == 0 if i % 3 == 0
continue continue
end end
print(i, " ") print(i, " ")
end end
``` ```
%% Cell type:markdown id:b8eac9e9-dff9-4b86-88a7-e14f27b7f677 tags: %% Cell type:markdown id:b8eac9e9-dff9-4b86-88a7-e14f27b7f677 tags:
For more detials: [https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration](https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration). For more detials: [https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration](https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration).
%% Cell type:markdown id:d2e93721 tags: %% Cell type:markdown id:d2e93721 tags:
Für weitere Details: [https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration](https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration). Für weitere Details: [https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration](https://docs.julialang.org/en/v1/base/collections/#lib-collections-iteration).
%% Cell type:markdown id:990cefae-abfe-4649-8d68-3fac1b1e268b tags: %% Cell type:markdown id:990cefae-abfe-4649-8d68-3fac1b1e268b tags:
### Exercises ### Exercises
%% Cell type:markdown id:625f1e1b-ab4d-425d-b848-94385ddcb690 tags: %% Cell type:markdown id:625f1e1b-ab4d-425d-b848-94385ddcb690 tags:
### Übungen ### Übungen
%% Cell type:markdown id:bdb2eef9-bdee-4cf3-8bab-d6c1d46ecc2f tags: %% Cell type:markdown id:bdb2eef9-bdee-4cf3-8bab-d6c1d46ecc2f tags:
The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/π The mathematician Srinivasa Ramanujan found an infinite series that can be used to generate a numerical approximation of 1/π
$$ \frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum_{k=0}^\infty \frac{(4k)! (1103 + 26390 k)}{(k!)^4 396^{4 k}}$$ $$ \frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum_{k=0}^\infty \frac{(4k)! (1103 + 26390 k)}{(k!)^4 396^{4 k}}$$
Use this formula to compute an estimate of π. It should use a while loop ot compute terms of the summation untile the last term is smaller than 1e-15. Afterwards, you can check the result by comparing it to π (to get π in Julia, write \pi and then press TAB). Use this formula to compute an estimate of π. It should use a while loop ot compute terms of the summation untile the last term is smaller than 1e-15. Afterwards, you can check the result by comparing it to π (to get π in Julia, write \pi and then press TAB). Hint: use the builtin function `factorial`.
%% Cell type:markdown id:6a0dcd06-0926-4529-ac33-0aee315f85cf tags: %% Cell type:markdown id:6a0dcd06-0926-4529-ac33-0aee315f85cf tags:
Der Mathematiker Srinivasa Ramanujan fand eine unendliche Reihe, die verwendet werden kann, um eine numerische Näherung von 1/π zu generieren: Der Mathematiker Srinivasa Ramanujan fand eine unendliche Reihe, die verwendet werden kann, um eine numerische Näherung von 1/π zu generieren:
$$ \frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum_{k=0}^\infty \frac{(4k)! (1103 + 26390 k)}{(k!)^4 396^{4 k}}$$ $$ \frac{1}{\pi} = \frac{2\sqrt{2}}{9801} \sum_{k=0}^\infty \frac{(4k)! (1103 + 26390 k)}{(k!)^4 396^{4 k}}$$
Verwenden Sie diese Formel, um eine Schätzung von π zu berechnen. Sie sollte eine While-Schleife verwenden, um die Terme der Summation zu berechnen, bis der letzte Term kleiner als 1e-15 ist. Anschließend können Sie das Ergebnis überprüfen, indem Sie es mit π vergleichen (um π in Julia zu erhalten, schreiben Sie \pi und drücken dann die TAB-Taste). Verwenden Sie diese Formel, um eine Schätzung von π zu berechnen. Sie sollte eine While-Schleife verwenden, um die Terme der Summation zu berechnen, bis der letzte Term kleiner als 1e-15 ist. Anschließend können Sie das Ergebnis überprüfen, indem Sie es mit π vergleichen (um π in Julia zu erhalten, schreiben Sie \pi und drücken dann die TAB-Taste). Hinweis: Verwenden Sie die integrierte Funktion `factorial`.
%% Cell type:code id:9243c8ee-b3b9-4e23-a829-d20fc8bf0b16 tags:
``` julia
factorial(3)
```
%% Cell type:code id:dbe40300-8333-4271-aa43-49f973fa03a6 tags: %% Cell type:code id:dbe40300-8333-4271-aa43-49f973fa03a6 tags:
``` julia ``` julia
n = 3
number = 0
for k in 0:n
number += factorial(4*k)*(1103.0+26390.0*k)/(factorial(k)^4.0*396.0^(4.0*k))
end
number *= 2*sqrt(2)/9801
print(number," ")
print(1.0/number-π)
``` ```
%% Cell type:markdown id:d4a870c3-7679-4775-94ce-4e7266a2bebe tags: %% Cell type:markdown id:d4a870c3-7679-4775-94ce-4e7266a2bebe tags:
## Functions ## Functions
%% Cell type:markdown id:e2072b09-53e0-4354-984b-13813e93fef1 tags: %% Cell type:markdown id:e2072b09-53e0-4354-984b-13813e93fef1 tags:
## Funktionen ## Funktionen
%% Cell type:markdown id:682a3feb-0b82-479d-9803-3011a1e6e521 tags: %% Cell type:markdown id:682a3feb-0b82-479d-9803-3011a1e6e521 tags:
We have already seen one example of a function call: We have already seen one example of a function call:
%% Cell type:markdown id:8fde350c-f73a-44b7-9459-b8f6d79120cf tags: %% Cell type:markdown id:8fde350c-f73a-44b7-9459-b8f6d79120cf tags:
Wir haben bereits ein Beispiel für einen Funktionsaufruf gesehen: Wir haben bereits ein Beispiel für einen Funktionsaufruf gesehen:
%% Cell type:code id:addaa346-7a88-4c18-9f1e-295665959a9d tags: %% Cell type:code id:addaa346-7a88-4c18-9f1e-295665959a9d tags:
``` julia ``` julia
println("Hello, World!") println("Hello, World!")
``` ```
%% Cell type:markdown id:3434842c-2af0-4f6a-a70b-a59fb8fcc4af tags: %% Cell type:markdown id:3434842c-2af0-4f6a-a70b-a59fb8fcc4af tags:
The name of the function is println. The expression in parentheses is called the argument of the function. The name of the function is println. The expression in parentheses is called the argument of the function.
It is common to say that a function “takes” an argument and “returns” a result. The result is also called the return value. It is common to say that a function “takes” an argument and “returns” a result. The result is also called the return value.
%% Cell type:markdown id:ef1e8206-add5-49f9-ab4c-4b730164aee6 tags: %% Cell type:markdown id:ef1e8206-add5-49f9-ab4c-4b730164aee6 tags:
Der Name der Funktion ist println. Der Ausdruck in Klammern wird als Argument der Funktion bezeichnet. Der Name der Funktion ist println. Der Ausdruck in Klammern wird als Argument der Funktion bezeichnet.
Es ist üblich zu sagen, dass eine Funktion ein Argument "nimmt" und ein Ergebnis "zurückgibt". Das Ergebnis wird auch als Rückgabewert bezeichnet. Es ist üblich zu sagen, dass eine Funktion ein Argument "nimmt" und ein Ergebnis "zurückgibt". Das Ergebnis wird auch als Rückgabewert bezeichnet.
%% Cell type:markdown id:f63d270a-7149-4ffd-bc31-f746560a37ac tags: %% Cell type:markdown id:f63d270a-7149-4ffd-bc31-f746560a37ac tags:
Julia provides functions that convert values from one type to another. The parse function takes a string and converts it to any number type, if it can, or complains otherwise: Julia provides functions that convert values from one type to another. The parse function takes a string and converts it to any number type, if it can, or complains otherwise:
%% Cell type:markdown id:bd083417-b51a-4f0e-a150-56a0f9c33569 tags: %% Cell type:markdown id:bd083417-b51a-4f0e-a150-56a0f9c33569 tags:
Julia bietet Funktionen, die Werte von einem Typ in einen anderen konvertieren. Die Funktion `parse` nimmt einen String und wandelt ihn in jeden Zahlen-Typ um, wenn es möglich ist, oder gibt andernfalls eine Fehlermeldung aus: Julia bietet Funktionen, die Werte von einem Typ in einen anderen konvertieren. Die Funktion `parse` nimmt einen String und wandelt ihn in jeden Zahlen-Typ um, wenn es möglich ist, oder gibt andernfalls eine Fehlermeldung aus:
%% Cell type:code id:1f05465a-4863-4205-9c73-26f0e93f049b tags: %% Cell type:code id:1f05465a-4863-4205-9c73-26f0e93f049b tags:
``` julia ``` julia
parse(Int64, "32") parse(Int64, "32")
``` ```
%% Cell type:code id:e6ac9994-9cbb-4004-889d-a657b8396063 tags: %% Cell type:code id:e6ac9994-9cbb-4004-889d-a657b8396063 tags:
``` julia ``` julia
parse(Int64, "Hello") parse(Int64, "Hello")
``` ```
%% Cell type:markdown id:793c9620-7b6e-443c-8765-8136fbfcb071 tags: %% Cell type:markdown id:793c9620-7b6e-443c-8765-8136fbfcb071 tags:
Julia provides several mathematical functions. Julia provides several mathematical functions.
- abs, sqrt, cbrt, exp, log, log10, log2 - abs, sqrt, cbrt, exp, log, log10, log2
- sin, cos, tan, asin, acos, atan - sin, cos, tan, asin, acos, atan
- sinh, cosh, tanh, asinh, acosh, atanh - sinh, cosh, tanh, asinh, acosh, atanh
- floor: Largest integer not greater than x. - floor: Largest integer not greater than x.
- ceil: Smallest integer not less than x. - ceil: Smallest integer not less than x.
- round: Nearest integer to x. - round: Nearest integer to x.
- trunc: Integer part of x. - trunc: Integer part of x.
For more details: [https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions](https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions). For more details: [https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions](https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions).
%% Cell type:markdown id:9176592b-e9f3-46fd-9909-8b73da750434 tags: %% Cell type:markdown id:9176592b-e9f3-46fd-9909-8b73da750434 tags:
Julia stellt verschiedene mathematische Funktionen zur Verfügung: Julia stellt verschiedene mathematische Funktionen zur Verfügung:
- abs, sqrt, cbrt, exp, log, log10, log2 - abs, sqrt, cbrt, exp, log, log10, log2
- sin, cos, tan, asin, acos, atan - sin, cos, tan, asin, acos, atan
- sinh, cosh, tanh, asinh, acosh, atanh - sinh, cosh, tanh, asinh, acosh, atanh
- floor: Größte ganze Zahl, die nicht größer als x ist. - floor: Größte ganze Zahl, die nicht größer als x ist.
- ceil: Kleinste ganze Zahl, die nicht kleiner als x ist. - ceil: Kleinste ganze Zahl, die nicht kleiner als x ist.
- round: Nächstgelegene ganze Zahl zu x. - round: Nächstgelegene ganze Zahl zu x.
- trunc: Ganzzahliger Teil von x. - trunc: Ganzzahliger Teil von x.
Für weitere Details: [https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions](https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions). Für weitere Details: [https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions](https://docs.julialang.org/en/v1/base/math/#Mathematical-Functions).
%% Cell type:markdown id:d048851b-8eac-4dc3-81b7-ea1d625a1db2 tags: %% Cell type:markdown id:d048851b-8eac-4dc3-81b7-ea1d625a1db2 tags:
So far, we have only been using the functions that come with Julia, but it is also possible to add new functions. So far, we have only been using the functions that come with Julia, but it is also possible to add new functions.
Defining functions follows a rather intuitive syntax. The value obtained by evaluating the last expression of a `function` block will be automatically returned: Defining functions follows a rather intuitive syntax. The value obtained by evaluating the last expression of a `function` block will be automatically returned:
%% Cell type:markdown id:f43cb468-832a-4cab-b8a3-15bb9bcbfb0d tags: %% Cell type:markdown id:f43cb468-832a-4cab-b8a3-15bb9bcbfb0d tags:
Bisher haben wir nur die Funktionen verwendet, die mit Julia geliefert werden, aber es ist auch möglich, neue Funktionen hinzuzufügen. Bisher haben wir nur die Funktionen verwendet, die mit Julia geliefert werden, aber es ist auch möglich, neue Funktionen hinzuzufügen.
Die Definition von Funktionen folgt einer recht intuitiven Syntax. Der Wert, der durch Auswerten des letzten Ausdrucks eines `function`-Blocks erhalten wird, wird automatisch zurückgegeben: Die Definition von Funktionen folgt einer recht intuitiven Syntax. Der Wert, der durch Auswerten des letzten Ausdrucks eines `function`-Blocks erhalten wird, wird automatisch zurückgegeben:
%% Cell type:code id:fd2f4828-47f5-4df4-b5bd-a42625487b5a tags: %% Cell type:code id:fd2f4828-47f5-4df4-b5bd-a42625487b5a tags:
``` julia ``` julia
function mymult(x, y) function mymult(x, y)
x * y x * y
end end
``` ```
%% Cell type:markdown id:08bab11e-df61-4906-a925-b93184e5c600 tags: %% Cell type:markdown id:08bab11e-df61-4906-a925-b93184e5c600 tags:
For one-line functions one may also use a convenient short-hand: For one-line functions one may also use a convenient short-hand:
%% Cell type:markdown id:e8dfb238-54be-4a95-9eda-4ce1fa5cfd74 tags: %% Cell type:markdown id:e8dfb238-54be-4a95-9eda-4ce1fa5cfd74 tags:
Für Einzeiler-Funktionen kann man auch eine praktische Kurzschreibweise verwenden: Für Einzeiler-Funktionen kann man auch eine praktische Kurzschreibweise verwenden:
%% Cell type:code id:5ed8292a-96e2-49ad-8f00-3c07b9483637 tags: %% Cell type:code id:5ed8292a-96e2-49ad-8f00-3c07b9483637 tags:
``` julia ``` julia
mysquare(x) = mymult(x, x) mysquare(x) = mymult(x, x)
``` ```
%% Cell type:markdown id:13b7892e-df8a-462f-a84c-107276d8e499 tags: %% Cell type:markdown id:13b7892e-df8a-462f-a84c-107276d8e499 tags:
Both such functions are fully generic in the argument types Both such functions are fully generic in the argument types
%% Cell type:markdown id:9b688bbf-08b6-4fba-babe-b16b6e1119be tags: %% Cell type:markdown id:9b688bbf-08b6-4fba-babe-b16b6e1119be tags:
Beide Funktionen sind in den Argumenttypen vollständig generisch Beide Funktionen sind in den Argumenttypen vollständig generisch
%% Cell type:code id:49ceeeff-5291-460d-800d-5ed11a03b13e tags: %% Cell type:code id:49ceeeff-5291-460d-800d-5ed11a03b13e tags:
``` julia ``` julia
@show mysquare(2) # Use integer arithmetic @show mysquare(2) # Use integer arithmetic
@show mymult(-1, 3. + 2im) # Use complex arithmetic @show mymult(-1, 3. + 2im) # Use complex arithmetic
@show mysquare(" abc "); # Use string concatenation @show mysquare(" abc "); # Use string concatenation
``` ```
%% Cell type:markdown id:15ece147-0384-4c1b-a8c3-d11a795bd1b7 tags: %% Cell type:markdown id:15ece147-0384-4c1b-a8c3-d11a795bd1b7 tags:
Notice, that for each type combination a separate piece of code will be compiled even though we only *defined* the functionality a single time. This compilation takes place on first use of a particular tuple of types. Notice, that for each type combination a separate piece of code will be compiled even though we only *defined* the functionality a single time. This compilation takes place on first use of a particular tuple of types.
%% Cell type:markdown id:6add8ab6-7f66-431b-9e9e-e52d45379483 tags: %% Cell type:markdown id:6add8ab6-7f66-431b-9e9e-e52d45379483 tags:
Beachten Sie, dass für jede Kombination von Typen ein separater Codeabschnitt kompiliert wird, obwohl wir die Funktionalität nur einmal *definiert* haben. Diese Kompilierung findet beim ersten Gebrauch eines bestimmten Tupels von Typen statt. Beachten Sie, dass für jede Kombination von Typen ein separater Codeabschnitt kompiliert wird, obwohl wir die Funktionalität nur einmal *definiert* haben. Diese Kompilierung findet beim ersten Gebrauch eines bestimmten Tupels von Typen statt.
%% Cell type:code id:7e5dcfeb-960a-47f3-b2f8-f6f0906d2f24 tags: %% Cell type:code id:7e5dcfeb-960a-47f3-b2f8-f6f0906d2f24 tags:
``` julia ``` julia
mymult mymult
``` ```
%% Cell type:markdown id:934dc8e8-564b-4566-9eb0-a96df39f0870 tags: %% Cell type:markdown id:934dc8e8-564b-4566-9eb0-a96df39f0870 tags:
and may be passed around to other functions, for example: and may be passed around to other functions, for example:
%% Cell type:markdown id:3be89ab5-16f3-4633-bb8d-fd74cf39ddec tags: %% Cell type:markdown id:3be89ab5-16f3-4633-bb8d-fd74cf39ddec tags:
und können an andere Funktionen übergeben werden, zum Beispiel: und können an andere Funktionen übergeben werden, zum Beispiel:
%% Cell type:code id:171b1a83-c076-4ac4-a309-9d607ea0b5a4 tags: %% Cell type:code id:171b1a83-c076-4ac4-a309-9d607ea0b5a4 tags:
``` julia ``` julia
"""The fold function, applying f from the left and accumulating the results""" """The fold function, applying f from the left and accumulating the results"""
function myfold(f, x, y, z) function myfold(f, x, y, z)
f(f(x, y), z) f(f(x, y), z)
end end
myfold(mymult, "Hello", " Julia ", "World") myfold(mymult, "Hello", " Julia ", "World")
``` ```
%% Cell type:markdown id:f31327e4-5d69-4dfb-a4bf-ed1e419b1be3 tags: %% Cell type:markdown id:f31327e4-5d69-4dfb-a4bf-ed1e419b1be3 tags:
Julia makes a distinction between **functions** and **methods**. Roughly speaking **function**s specify *what* is done and **methods** specify *how* this is done. Julia makes a distinction between **functions** and **methods**. Roughly speaking **function**s specify *what* is done and **methods** specify *how* this is done.
Methods are concrete implementations in form of a list of Julia expressions to be executed, when the function name is used in the code. Multiple methods may be defined for the same function name. They differ in the number of arguments or in the supported argument types (more on this in the next notebook). When a particular function name is used in the code, Julia looks at the types of the arguments and uses this information to **dispatch** to the best-fitting method. Methods are concrete implementations in form of a list of Julia expressions to be executed, when the function name is used in the code. Multiple methods may be defined for the same function name. They differ in the number of arguments or in the supported argument types (more on this in the next notebook). When a particular function name is used in the code, Julia looks at the types of the arguments and uses this information to **dispatch** to the best-fitting method.
For our `myfold` example, one could easily imagine a few more method implementations, for example: For our `myfold` example, one could easily imagine a few more method implementations, for example:
%% Cell type:markdown id:09a40182-e59f-42e4-b11e-0c3aedd0e7a6 tags: %% Cell type:markdown id:09a40182-e59f-42e4-b11e-0c3aedd0e7a6 tags:
Julia unterscheidet zwischen **Funktionen** und **Methoden**. Grob gesagt geben **Funktionen** an, *was* gemacht wird, und **Methoden** geben an, *wie* dies gemacht wird. Julia unterscheidet zwischen **Funktionen** und **Methoden**. Grob gesagt geben **Funktionen** an, *was* gemacht wird, und **Methoden** geben an, *wie* dies gemacht wird.
Methoden sind konkrete Implementierungen in Form von einer Liste von Julia-Ausdrücken, die ausgeführt werden, wenn der Funktionsname im Code verwendet wird. Für den gleichen Funktionsnamen können mehrere Methoden definiert werden. Sie unterscheiden sich in der Anzahl der Argumente oder in den unterstützten Argumenttypen (dazu mehr im nächsten Notebook). Wenn ein bestimmter Funktionsname im Code verwendet wird, betrachtet Julia die Typen der Argumente und verwendet diese Informationen, um zur am besten passenden Methode zu **dispatchen**. Methoden sind konkrete Implementierungen in Form von einer Liste von Julia-Ausdrücken, die ausgeführt werden, wenn der Funktionsname im Code verwendet wird. Für den gleichen Funktionsnamen können mehrere Methoden definiert werden. Sie unterscheiden sich in der Anzahl der Argumente oder in den unterstützten Argumenttypen (dazu mehr im nächsten Notebook). Wenn ein bestimmter Funktionsname im Code verwendet wird, betrachtet Julia die Typen der Argumente und verwendet diese Informationen, um zur am besten passenden Methode zu **dispatchen**.
Für unser `myfold`-Beispiel könnte man sich leicht einige weitere Methodenimplementierungen vorstellen, zum Beispiel: Für unser `myfold`-Beispiel könnte man sich leicht einige weitere Methodenimplementierungen vorstellen, zum Beispiel:
%% Cell type:code id:c249f818-6544-42fe-b387-34058e5f5890 tags: %% Cell type:code id:c249f818-6544-42fe-b387-34058e5f5890 tags:
``` julia ``` julia
myfold(f, x) = x myfold(f, x) = x
myfold(f, x, y) = f(x, y) myfold(f, x, y) = f(x, y)
``` ```
%% Cell type:code id:88f62159-2a1b-4a5a-8434-0e91810f2c69 tags: %% Cell type:code id:88f62159-2a1b-4a5a-8434-0e91810f2c69 tags:
``` julia ``` julia
methods(myfold) methods(myfold)
``` ```
%% Cell type:markdown id:879d9441-ece1-4f07-a496-6aef71fd2e91 tags: %% Cell type:markdown id:879d9441-ece1-4f07-a496-6aef71fd2e91 tags:
So now `myfold` works transparently with 1, 2 or 3 arguments: So now `myfold` works transparently with 1, 2 or 3 arguments:
%% Cell type:markdown id:cc818df4-a037-4ba2-8588-1afe4a6de222 tags: %% Cell type:markdown id:cc818df4-a037-4ba2-8588-1afe4a6de222 tags:
Nun funktioniert `myfold` transparent mit 1, 2 oder 3 Argumenten: Nun funktioniert `myfold` transparent mit 1, 2 oder 3 Argumenten:
%% Cell type:code id:d67f9c21-2c5c-43fd-a7e4-a4ce74281bf0 tags: %% Cell type:code id:d67f9c21-2c5c-43fd-a7e4-a4ce74281bf0 tags:
``` julia ``` julia
@show myfold(mymult, 2., 3.) @show myfold(mymult, 2., 3.)
@show myfold(+, 1) @show myfold(+, 1)
@show myfold(==, false, false, true) @show myfold(==, false, false, true)
``` ```
%% Cell type:markdown id:59fa4c2a-a1fa-4a1b-9529-68f821589206 tags: %% Cell type:markdown id:59fa4c2a-a1fa-4a1b-9529-68f821589206 tags:
We can also check which method is actually employed using the `@which` macro: We can also check which method is actually employed using the `@which` macro:
%% Cell type:markdown id:5a9a652b-80c4-482f-80b8-2c5340e61a21 tags: %% Cell type:markdown id:5a9a652b-80c4-482f-80b8-2c5340e61a21 tags:
Wir können auch überprüfen, welche Methode tatsächlich verwendet wird, indem wir das `@which`-Makro verwenden: Wir können auch überprüfen, welche Methode tatsächlich verwendet wird, indem wir das `@which`-Makro verwenden:
%% Cell type:code id:0fa105fb-b3ad-405a-85f1-598a12cbc655 tags: %% Cell type:code id:0fa105fb-b3ad-405a-85f1-598a12cbc655 tags:
``` julia ``` julia
@which myfold(*, 1, 2) @which myfold(*, 1, 2)
``` ```
%% Cell type:markdown id:73fa3be7-67a8-4817-9d94-e04765513dd3 tags: %% Cell type:markdown id:73fa3be7-67a8-4817-9d94-e04765513dd3 tags:
Standard functions (like `+` or `*`) are by no means special and behave exactly the same way as custom functions ... including the ability to define new methods for them: Standard functions (like `+` or `*`) are by no means special and behave exactly the same way as custom functions ... including the ability to define new methods for them:
%% Cell type:markdown id:4046d2e8-2018-4f4f-b816-2a6156301f39 tags: %% Cell type:markdown id:4046d2e8-2018-4f4f-b816-2a6156301f39 tags:
Standardfunktionen (wie `+` oder `*`) sind keineswegs speziell und verhalten sich genau wie benutzerdefinierte Funktionen ... einschließlich der Möglichkeit, neue Methoden für sie zu definieren: Standardfunktionen (wie `+` oder `*`) sind keineswegs speziell und verhalten sich genau wie benutzerdefinierte Funktionen ... einschließlich der Möglichkeit, neue Methoden für sie zu definieren:
%% Cell type:code id:d771af33-5174-4a95-b8e3-ac1c29eb71e9 tags: %% Cell type:code id:d771af33-5174-4a95-b8e3-ac1c29eb71e9 tags:
``` julia ``` julia
import Base: + # we have to import functions to override/extend them import Base: + # we have to import functions to override/extend them
+(x::String, y::String) = x * " " * y +(x::String, y::String) = x * " " * y
``` ```
%% Cell type:code id:32429003-4879-4a37-ad3c-153857a360dd tags: %% Cell type:code id:32429003-4879-4a37-ad3c-153857a360dd tags:
``` julia ``` julia
"Hello" + "World!" "Hello" + "World!"
``` ```
%% Cell type:markdown id:8fdf6362-7ca3-4d32-a542-26df56b83108 tags: %% Cell type:markdown id:8fdf6362-7ca3-4d32-a542-26df56b83108 tags:
(**Important note:** Since we neither own the `+` function nor the `String` type, this is known as **type piracy** and should in general be avoided!) (**Important note:** Since we neither own the `+` function nor the `String` type, this is known as **type piracy** and should in general be avoided!)
%% Cell type:markdown id:ee25eff6-f56e-4230-b52d-6020dcc29bb2 tags: %% Cell type:markdown id:ee25eff6-f56e-4230-b52d-6020dcc29bb2 tags:
(**Wichtiger Hinweis:** Da wir weder die `+` Funktion noch den `String` Typ besitzen, handelt es sich hierbei um **Typenpiraterie** und sollte im Allgemeinen vermieden werden!) (**Wichtiger Hinweis:** Da wir weder die `+` Funktion noch den `String` Typ besitzen, handelt es sich hierbei um **Typenpiraterie** und sollte im Allgemeinen vermieden werden!)
%% Cell type:markdown id:89ffcdef-cf06-438f-8448-4bf6dfd1af7e tags: %% Cell type:markdown id:89ffcdef-cf06-438f-8448-4bf6dfd1af7e tags:
Now standard functions relying on `+` just magically work: Now standard functions relying on `+` just magically work:
%% Cell type:markdown id:a2c9d8cf-0462-415c-a466-edb33b3aadec tags: %% Cell type:markdown id:a2c9d8cf-0462-415c-a466-edb33b3aadec tags:
Nun funktionieren Standardfunktionen, die auf `+` angewiesen sind, einfach magisch: Nun funktionieren Standardfunktionen, die auf `+` angewiesen sind, einfach magisch:
%% Cell type:code id:75b4afeb-a3f4-40d7-8b23-b961b01c41bc tags: %% Cell type:code id:75b4afeb-a3f4-40d7-8b23-b961b01c41bc tags:
``` julia ``` julia
sum(["a", "b", "c", "d", "e"]) sum(["a", "b", "c", "d", "e"])
``` ```
%% Cell type:markdown id:d8edaaf0-3de7-4a63-b0bd-bff53ba060f4 tags: %% Cell type:markdown id:d8edaaf0-3de7-4a63-b0bd-bff53ba060f4 tags:
Variables and parameters are local, they exist only inside the functions where they are defined: Variables and parameters are local, they exist only inside the functions where they are defined:
%% Cell type:markdown id:013b3faf-5f12-482b-956e-de97a2a4830d tags: %% Cell type:markdown id:013b3faf-5f12-482b-956e-de97a2a4830d tags:
Variablen und Parameter sind lokal, sie existieren nur innerhalb der Funktionen, in denen sie definiert sind: Variablen und Parameter sind lokal, sie existieren nur innerhalb der Funktionen, in denen sie definiert sind:
%% Cell type:code id:d02e6bca-6723-4a05-82ee-1f30ba127bd5 tags: %% Cell type:code id:d02e6bca-6723-4a05-82ee-1f30ba127bd5 tags:
``` julia ``` julia
function multiply_and_print(a, b) function multiply_and_print(a, b)
product = a * b product = a * b
println(product) println(product)
end end
multiply_and_print(2, 3) multiply_and_print(2, 3)
println(product) println(product)
``` ```
%% Cell type:markdown id:29968f96-5766-4cb7-8538-3bef9aeb8cc9 tags: %% Cell type:markdown id:29968f96-5766-4cb7-8538-3bef9aeb8cc9 tags:
It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons: It may not be clear why it is worth the trouble to divide a program into functions. There are several reasons:
- Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug. - Creating a new function gives you an opportunity to name a group of statements, which makes your program easier to read and debug.
- Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place. - Functions can make a program smaller by eliminating repetitive code. Later, if you make a change, you only have to make it in one place.
- Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole. - Dividing a long program into functions allows you to debug the parts one at a time and then assemble them into a working whole.
- Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it. - Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
- In Julia, functions can improve performance a lot. - In Julia, functions can improve performance a lot.
%% Cell type:markdown id:0a398295-22e0-45dc-b43c-5f1915a16364 tags: %% Cell type:markdown id:0a398295-22e0-45dc-b43c-5f1915a16364 tags:
Es mag nicht klar sein, warum es sich lohnt, ein Programm in Funktionen zu unterteilen. Es gibt mehrere Gründe dafür: Es mag nicht klar sein, warum es sich lohnt, ein Programm in Funktionen zu unterteilen. Es gibt mehrere Gründe dafür:
- Das Erstellen einer neuen Funktion bietet die Möglichkeit, eine Gruppe von Anweisungen zu benennen, was das Programm leichter lesbar und einfacher zu debuggen macht. - Das Erstellen einer neuen Funktion bietet die Möglichkeit, eine Gruppe von Anweisungen zu benennen, was das Programm leichter lesbar und einfacher zu debuggen macht.
- Funktionen können ein Programm kleiner machen, indem sie wiederholten Code eliminieren. Später, wenn Sie eine Änderung vornehmen, müssen Sie sie nur an einer Stelle vornehmen. - Funktionen können ein Programm kleiner machen, indem sie wiederholten Code eliminieren. Später, wenn Sie eine Änderung vornehmen, müssen Sie sie nur an einer Stelle vornehmen.
- Das Aufteilen eines langen Programms in Funktionen ermöglicht es Ihnen, die Teile nacheinander zu debuggen und dann zu einem funktionierenden Ganzen zusammenzufügen. - Das Aufteilen eines langen Programms in Funktionen ermöglicht es Ihnen, die Teile nacheinander zu debuggen und dann zu einem funktionierenden Ganzen zusammenzufügen.
- Gut gestaltete Funktionen sind oft für viele Programme nützlich. Sobald Sie eine geschrieben und debuggt haben, können Sie sie wiederverwenden. - Gut gestaltete Funktionen sind oft für viele Programme nützlich. Sobald Sie eine geschrieben und debuggt haben, können Sie sie wiederverwenden.
- In Julia können Funktionen die Schnelligkeit erheblich verbessern. - In Julia können Funktionen die Schnelligkeit erheblich verbessern.
%% Cell type:markdown id:7780ae66-db68-48c1-ba62-a883406f1f1c tags: %% Cell type:markdown id:7780ae66-db68-48c1-ba62-a883406f1f1c tags:
More details: [https://docs.julialang.org/en/v1/manual/methods/](https://docs.julialang.org/en/v1/manual/methods/) More details: [https://docs.julialang.org/en/v1/manual/methods/](https://docs.julialang.org/en/v1/manual/methods/)
%% Cell type:markdown id:dfa722c2-bd4c-4162-b10d-24c0f8e990e0 tags: %% Cell type:markdown id:dfa722c2-bd4c-4162-b10d-24c0f8e990e0 tags:
Weitere Details finden Sie unter: [https://docs.julialang.org/en/v1/manual/methods/](https://docs.julialang.org/en/v1/manual/methods/) Weitere Details finden Sie unter: [https://docs.julialang.org/en/v1/manual/methods/](https://docs.julialang.org/en/v1/manual/methods/)
%% Cell type:markdown id:d914b36b-8b05-4c68-bf57-1fc74aeb26df tags: %% Cell type:markdown id:d914b36b-8b05-4c68-bf57-1fc74aeb26df tags:
### Exercises ### Exercises
%% Cell type:markdown id:a4eafce6-b493-470f-86a3-93319684ee40 tags: %% Cell type:markdown id:a4eafce6-b493-470f-86a3-93319684ee40 tags:
### Übungen ### Übungen
%% Cell type:markdown id:247215e4-47e1-4eb6-978b-a09f14478bb8 tags: %% Cell type:markdown id:247215e4-47e1-4eb6-978b-a09f14478bb8 tags:
- Write a function `printgrid` that draws a grid like the following: - Write a function `printgrid` that draws a grid like the following:
%% Cell type:markdown id:08fe364b-e611-419b-97f2-e806881d6227 tags: %% Cell type:markdown id:08fe364b-e611-419b-97f2-e806881d6227 tags:
- Schreiben Sie eine Funktion `printgrid`, die ein Raster wie folgt zeichnet: - Schreiben Sie eine Funktion `printgrid`, die ein Raster wie folgt zeichnet:
%% Cell type:markdown id:1704f451-9500-41c5-b74b-4a2b4a7b910f tags: %% Cell type:markdown id:1704f451-9500-41c5-b74b-4a2b4a7b910f tags:
+ - - - - + - - - - + + - - - - + - - - - +
| | | | | |
| | | | | |
| | | | | |
| | | | | |
+ - - - - + - - - - + + - - - - + - - - - +
| | | | | |
| | | | | |
| | | | | |
| | | | | |
+ - - - - + - - - - + + - - - - + - - - - +
%% Cell type:code id:58ef3248-f85e-4825-bf10-02cee3e068cb tags: %% Cell type:code id:58ef3248-f85e-4825-bf10-02cee3e068cb tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:e6a58742-9d24-47a5-aa68-73d44ca05127 tags: %% Cell type:markdown id:e6a58742-9d24-47a5-aa68-73d44ca05127 tags:
- Write a function that draws a similar grid with four rows and four columns. - Write a function that draws a similar grid with four rows and four columns.
%% Cell type:markdown id:41f2bf0f-73f4-4671-b059-1118c35ec76f tags: %% Cell type:markdown id:41f2bf0f-73f4-4671-b059-1118c35ec76f tags:
- Schreiben Sie eine Funktion, die ein ähnliches Raster mit vier Zeilen und vier Spalten zeichnet. - Schreiben Sie eine Funktion, die ein ähnliches Raster mit vier Zeilen und vier Spalten zeichnet.
%% Cell type:markdown id:b953857f-e8d7-47aa-bc8d-8e2bd1cd20fd tags: %% Cell type:markdown id:b953857f-e8d7-47aa-bc8d-8e2bd1cd20fd tags:
Tips: Tips:
- To print more than one value on a line, you can print a comma-separated sequence of values: println("+", "-"). - To print more than one value on a line, you can print a comma-separated sequence of values: println("+", "-").
- The function print does not advance to the next line. - The function print does not advance to the next line.
%% Cell type:markdown id:2e606498-6553-4037-a9f9-3b519ffc64c9 tags: %% Cell type:markdown id:2e606498-6553-4037-a9f9-3b519ffc64c9 tags:
Tipps: Tipps:
- Um mehr als einen Wert in einer Zeile auszugeben, können Sie eine kommagetrennte Sequenz von Werten ausgeben: println("+", "-"). - Um mehr als einen Wert in einer Zeile auszugeben, können Sie eine kommagetrennte Sequenz von Werten ausgeben: println("+", "-").
- Die Funktion print springt nicht zur nächsten Zeile. - Die Funktion print springt nicht zur nächsten Zeile.
%% Cell type:code id:1ca1789d-eddb-4f41-9ad9-9259c6f22a14 tags: %% Cell type:code id:1ca1789d-eddb-4f41-9ad9-9259c6f22a14 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:2ebc911c-7fe0-4d7f-ab5d-d8084f25a93d tags: %% Cell type:markdown id:2ebc911c-7fe0-4d7f-ab5d-d8084f25a93d tags:
### Recursive functions ### Recursive functions
It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function: It is legal for one function to call another; it is also legal for a function to call itself. It may not be obvious why that is a good thing, but it turns out to be one of the most magical things a program can do. For example, look at the following function:
%% Cell type:markdown id:53edcb8b-2f37-404f-8df6-d84b2327e96e tags: %% Cell type:markdown id:53edcb8b-2f37-404f-8df6-d84b2327e96e tags:
### Rekursive Funktionen ### Rekursive Funktionen
Es ist erlaubt, dass eine Funktion eine andere aufruft; es ist auch erlaubt, dass eine Funktion sich selbst aufruft. Es mag nicht offensichtlich sein, warum das eine gute Sache ist, aber es stellt sich heraus, dass es eine der magischsten Dinge ist, die ein Programm tun kann. Schauen Sie sich zum Beispiel die folgende Funktion an: Es ist erlaubt, dass eine Funktion eine andere aufruft; es ist auch erlaubt, dass eine Funktion sich selbst aufruft. Es mag nicht offensichtlich sein, warum das eine gute Sache ist, aber es stellt sich heraus, dass es eine der magischsten Dinge ist, die ein Programm tun kann. Schauen Sie sich zum Beispiel die folgende Funktion an:
%% Cell type:code id:e578011e-d0de-4f86-8c2c-a8408454d3ac tags: %% Cell type:code id:e578011e-d0de-4f86-8c2c-a8408454d3ac tags:
``` julia ``` julia
function countdown(n) function countdown(n)
if n ≤ 0 if n ≤ 0
println("Blastoff!") println("Blastoff!")
else else
print(n, " ") print(n, " ")
countdown(n-1) countdown(n-1)
end end
end end
``` ```
%% Cell type:code id:3af51513-c92e-4488-b2fe-243e2fef6b95 tags: %% Cell type:code id:3af51513-c92e-4488-b2fe-243e2fef6b95 tags:
``` julia ``` julia
countdown(10) countdown(10)
``` ```
%% Cell type:markdown id:c59c0f54-d967-4416-b57c-e855dfc2c350 tags: %% Cell type:markdown id:c59c0f54-d967-4416-b57c-e855dfc2c350 tags:
If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. Here is a minimal program with an infinite recursion: If a recursion never reaches a base case, it goes on making recursive calls forever, and the program never terminates. This is known as infinite recursion, and it is generally not a good idea. Here is a minimal program with an infinite recursion:
%% Cell type:markdown id:73ea203a-3919-4e14-b50f-22c8362eb771 tags: %% Cell type:markdown id:73ea203a-3919-4e14-b50f-22c8362eb771 tags:
Wenn eine Rekursion niemals einen Basisfall erreicht, macht sie unendliche rekursive Aufrufe, und das Programm terminiert nie. Dies wird als unendliche Rekursion bezeichnet und ist im Allgemeinen keine gute Idee. Hier ist ein minimales Programm mit einer unendlichen Rekursion: Wenn eine Rekursion niemals einen Basisfall erreicht, macht sie unendliche rekursive Aufrufe, und das Programm terminiert nie. Dies wird als unendliche Rekursion bezeichnet und ist im Allgemeinen keine gute Idee. Hier ist ein minimales Programm mit einer unendlichen Rekursion:
%% Cell type:code id:13a4a762-6584-47ab-9fb5-428557770d15 tags: %% Cell type:code id:13a4a762-6584-47ab-9fb5-428557770d15 tags:
``` julia ``` julia
function recurse() function recurse()
recurse() recurse()
end end
``` ```
%% Cell type:code id:0dde579f-6b12-4072-aa62-aeee3a970503 tags: %% Cell type:code id:0dde579f-6b12-4072-aa62-aeee3a970503 tags:
``` julia ``` julia
recurse() recurse()
``` ```
%% Cell type:markdown id:22c8c79d-6d41-4758-9550-aaab4f1dc1b1 tags: %% Cell type:markdown id:22c8c79d-6d41-4758-9550-aaab4f1dc1b1 tags:
### Exercises ### Exercises
- Write a recursive function to compute the factorial of a number. - Write a recursive function to compute the factorial of a number.
%% Cell type:markdown id:a0402c3d-95fa-44a1-86ab-ca229508f68f tags: %% Cell type:markdown id:a0402c3d-95fa-44a1-86ab-ca229508f68f tags:
### Übungen ### Übungen
- Schreiben Sie eine rekursive Funktion zur Berechnung der Fakultät einer Zahl. - Schreiben Sie eine rekursive Funktion zur Berechnung der Fakultät einer Zahl.
%% Cell type:code id:f4102487-011e-474f-ab79-3d7db1d3bbd9 tags: %% Cell type:code id:f4102487-011e-474f-ab79-3d7db1d3bbd9 tags:
``` julia ``` julia
function myfrac(n)
r =
if n>1
r = n*myfrac(n-1)
else
r = 1
end
r
end
```
%% Cell type:code id:e7258177-64a5-4f00-ab48-9b78665695c8 tags:
``` julia
myfrac(4)
``` ```
%% Cell type:markdown id:d9c31712-941c-4611-99e5-b33cdb12e28f tags: %% Cell type:markdown id:d9c31712-941c-4611-99e5-b33cdb12e28f tags:
- Then write a function that computes bynomial coefficients - Then write a function that computes binomial coefficients
$$ \left(\begin{array}{c} n \\ k \end{array}\right) = \frac{n!}{k! (n-k)!} $$ $$ \left(\begin{array}{c} n \\ k \end{array}\right) = \frac{n!}{k! (n-k)!} $$
by calling the function of the previous points. by calling the function of the previous points.
%% Cell type:markdown id:a24cdaef-98b8-46f5-a809-992547882a4b tags: %% Cell type:markdown id:a24cdaef-98b8-46f5-a809-992547882a4b tags:
- Schreiben Sie dann eine Funktion, die die Binomialkoeffizienten berechnet - Schreiben Sie dann eine Funktion, die die Binomialkoeffizienten berechnet
$$ \left(\begin{array}{c} n \\ k \end{array}\right) = \frac{n!}{k! (n-k)!} $$ $$ \left(\begin{array}{c} n \\ k \end{array}\right) = \frac{n!}{k! (n-k)!} $$
indem sie die Funktion aus den vorherigen Punkten aufruft. indem sie die Funktion aus den vorherigen Punkten aufruft.
%% Cell type:code id:b54c877e-5494-4657-ba7f-208bdc301225 tags: %% Cell type:code id:b54c877e-5494-4657-ba7f-208bdc301225 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:4509db3f-8060-46ca-89ac-824c16f5751c tags: %% Cell type:markdown id:4509db3f-8060-46ca-89ac-824c16f5751c tags:
- Use the two functions to compute - Use the two functions to compute
$$ 15! \qquad \left(\begin{array}{c} 5 \\ 2 \end{array}\right) \qquad \left(\begin{array}{c} 5 \\ 3 \end{array}\right) $$ $$ 15! \qquad \left(\begin{array}{c} 5 \\ 2 \end{array}\right) \qquad \left(\begin{array}{c} 5 \\ 3 \end{array}\right) $$
%% Cell type:markdown id:a32900cc-c244-4d63-8ff6-4d11cee83eee tags: %% Cell type:markdown id:a32900cc-c244-4d63-8ff6-4d11cee83eee tags:
- Verwenden Sie die beiden Funktionen, um folgendes zu berechnen - Verwenden Sie die beiden Funktionen, um folgendes zu berechnen
$$ 15! \qquad \left(\begin{array}{c} 5 \\ 2 \end{array}\right) \qquad \left(\begin{array}{c} 5 \\ 3 \end{array}\right) $$ $$ 15! \qquad \left(\begin{array}{c} 5 \\ 2 \end{array}\right) \qquad \left(\begin{array}{c} 5 \\ 3 \end{array}\right) $$
%% Cell type:code id:fb02aad5-d9d4-4f0d-8118-b02b73506b89 tags: %% Cell type:code id:fb02aad5-d9d4-4f0d-8118-b02b73506b89 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:240cc4bd-3e45-45b8-ad98-170dbb68f78d tags: %% Cell type:markdown id:240cc4bd-3e45-45b8-ad98-170dbb68f78d tags:
### Keywords argument ### Keywords argument
Function arguments can be either position based (like what we saw so far) or keyword based, like in the following example. Function arguments can be either position based (like what we saw so far) or keyword based, like in the following example.
%% Cell type:markdown id:b5944412-0d39-4c0b-a0d5-fbeee22e1432 tags: %% Cell type:markdown id:b5944412-0d39-4c0b-a0d5-fbeee22e1432 tags:
### Schlüsselwortargumente ### Schlüsselwortargumente
Funktionsargumente können entweder positionsbasiert (wie wir bisher gesehen haben) oder schlüsselwortbasiert sein, wie im folgenden Beispiel. Funktionsargumente können entweder positionsbasiert (wie wir bisher gesehen haben) oder schlüsselwortbasiert sein, wie im folgenden Beispiel.
%% Cell type:code id:30ddeb3b-be35-40eb-8491-1269a4e19f62 tags: %% Cell type:code id:30ddeb3b-be35-40eb-8491-1269a4e19f62 tags:
``` julia ``` julia
function greet(name; greeting="Hello") function greet(name; greeting="Hello")
println("$(greeting), $(name)!") println("$(greeting), $(name)!")
end end
``` ```
%% Cell type:code id:b39f22b1-4a1b-4afd-b6db-041bd7150b66 tags: %% Cell type:code id:b39f22b1-4a1b-4afd-b6db-041bd7150b66 tags:
``` julia ``` julia
greet("Michele") greet("Michele")
greet("Lambert"; greeting="Hallo") greet("Lambert"; greeting="Hallo")
greet("YingXing"; greeting="你好") greet("YingXing"; greeting="你好")
``` ```
%% Cell type:markdown id:52b90aa8-4b19-4371-8fae-2121a78fbb96 tags: %% Cell type:markdown id:52b90aa8-4b19-4371-8fae-2121a78fbb96 tags:
This is quite convenient in the following cases: This is quite convenient in the following cases:
- to set a default behavior of the function, while retaining the possibility to finely control it. - to set a default behavior of the function, while retaining the possibility to finely control it.
- to add at a later point in time new functionality, without breaking retrocompatibility. - to add at a later point in time new functionality, without breaking retrocompatibility.
%% Cell type:markdown id:07e76016-d5a9-4616-b0b9-2dc9b6f3c8f6 tags: %% Cell type:markdown id:07e76016-d5a9-4616-b0b9-2dc9b6f3c8f6 tags:
Dies ist in den folgenden Fällen sehr praktisch: Dies ist in den folgenden Fällen sehr praktisch:
- um ein Standardverhalten der Funktion festzulegen, während die Möglichkeit besteht, sie fein zu steuern. - um ein Standardverhalten der Funktion festzulegen, während die Möglichkeit besteht, sie fein zu steuern.
- um zu einem späteren Zeitpunkt neue Funktionalitäten hinzuzufügen, ohne die Abwärtskompatibilität zu brechen. - um zu einem späteren Zeitpunkt neue Funktionalitäten hinzuzufügen, ohne die Abwärtskompatibilität zu brechen.
%% Cell type:markdown id:c939f951-2aaf-4e39-a60f-df7600af1d8f tags: %% Cell type:markdown id:c939f951-2aaf-4e39-a60f-df7600af1d8f tags:
## Further Exercises ## Further Exercises
%% Cell type:markdown id:883b3945-d30a-4f27-928f-458c9ad74e9b tags: %% Cell type:markdown id:883b3945-d30a-4f27-928f-458c9ad74e9b tags:
## Weitere Übungen ## Weitere Übungen
%% Cell type:markdown id:59e2e997-42f7-426c-bfd0-233724704117 tags: %% Cell type:markdown id:59e2e997-42f7-426c-bfd0-233724704117 tags:
- Create a function called `fibonacci_sum` that takes a positive integer n as input. This function should return the sum of the first n terms of the Fibonacci sequence. - Create a function called `fibonacci_sum` that takes a positive integer n as input. This function should return the sum of the first n terms of the Fibonacci sequence.
%% Cell type:markdown id:54537041-60eb-4961-9805-1d7d405fde1a tags: %% Cell type:markdown id:54537041-60eb-4961-9805-1d7d405fde1a tags:
- Erstellen Sie eine Funktion namens `fibonacci_sum`, die eine positive ganze Zahl n als Eingabe erhält. Diese Funktion sollte die Summe der ersten n Terme der Fibonacci-Folge zurückgeben. - Erstellen Sie eine Funktion namens `fibonacci_sum`, die eine positive ganze Zahl n als Eingabe erhält. Diese Funktion sollte die Summe der ersten n Terme der Fibonacci-Folge zurückgeben.
%% Cell type:code id:7ca7c936-fb80-4aed-9788-75a55bb207ad tags: %% Cell type:code id:7ca7c936-fb80-4aed-9788-75a55bb207ad tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:49fd546f-009d-46ff-af61-6954000bce5f tags: %% Cell type:markdown id:49fd546f-009d-46ff-af61-6954000bce5f tags:
- Write a function that converts a Celsius temperature in Fahrenheit and returns the result. Additionally, if the temperature is below freezing (0°C), the program should print a message indicating that it's below freezing. - Write a function that converts a Celsius temperature in Fahrenheit and returns the result. Additionally, if the temperature is below freezing (0°C), the program should print a message indicating that it's below freezing.
%% Cell type:markdown id:70dacb25-360f-4a7a-8c03-73cd0d75dc3e tags: %% Cell type:markdown id:70dacb25-360f-4a7a-8c03-73cd0d75dc3e tags:
- Schreiben Sie eine Funktion, die eine Celsius-Temperatur in Fahrenheit umrechnet und das Ergebnis zurückgibt. Zusätzlich sollte das Programm, wenn die Temperatur unter dem Gefrierpunkt (0°C) liegt, eine Meldung ausgeben, die anzeigt, dass es unter dem Gefrierpunkt liegt. - Schreiben Sie eine Funktion, die eine Celsius-Temperatur in Fahrenheit umrechnet und das Ergebnis zurückgibt. Zusätzlich sollte das Programm, wenn die Temperatur unter dem Gefrierpunkt (0°C) liegt, eine Meldung ausgeben, die anzeigt, dass es unter dem Gefrierpunkt liegt.
%% Cell type:code id:a30a1812-6116-4441-8786-7450c60ef354 tags: %% Cell type:code id:a30a1812-6116-4441-8786-7450c60ef354 tags:
``` julia ``` julia
``` ```
%% Cell type:markdown id:e2c81cc5-7d0d-4a5a-ba69-81686648df90 tags: %% Cell type:markdown id:e2c81cc5-7d0d-4a5a-ba69-81686648df90 tags:
- Write a function which analyzes a sentence. The function should then count and display the number of vowels (both upper and lower case) in the sentence. - Write a function which analyzes a sentence. The function should then count and display the number of vowels (both upper and lower case) in the sentence.
%% Cell type:markdown id:8cabe824-c7eb-46fc-afb8-e039528d2d2a tags: %% Cell type:markdown id:8cabe824-c7eb-46fc-afb8-e039528d2d2a tags:
- Schreiben Sie eine Funktion, die einen Satz analysiert. Die Funktion sollte dann die Anzahl der Vokale (sowohl in Groß- als auch in Kleinbuchstaben) im Satz zählen und anzeigen. - Schreiben Sie eine Funktion, die einen Satz analysiert. Die Funktion sollte dann die Anzahl der Vokale (sowohl in Groß- als auch in Kleinbuchstaben) im Satz zählen und anzeigen.
%% Cell type:code id:af0e28bd-2b3f-41af-aa92-456e29d50679 tags: %% Cell type:code id:af0e28bd-2b3f-41af-aa92-456e29d50679 tags:
``` julia ``` julia
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment