english improved

This commit is contained in:
2026-03-05 20:09:16 +01:00
parent c6609d15f5
commit 733fe8c290
21 changed files with 954 additions and 1042 deletions

View File

@@ -40,28 +40,27 @@ Base.active_module() = myactive_module()
## Console
The operating system normally provides 3 channels (_streams_) for a program:
The operating system typically provides three channels (_streams_) for a program:
- Standard input channel `stdin`
- Standard output channel `stdout` and
- Standard error output channel `stderr`.
- Standard input (`stdin`)
- Standard output (`stdout`)
- Standard error (`stderr`)
When the program is started in a terminal (or console or shell), the program can read keyboard input via `stdin` and output appears in the terminal via `stdout` and `stdout`.
When executed in a terminal, console, or shell, the program reads keyboard input through `stdin` and outputs to the terminal via `stdout` and `stderr`.
- Writing to `stdout`: `print()`,`println()`,`printstyled()`
- Writing to `stderr`: `print(strerr,...)`, `println(stderr,...)`, `printstyled(stderr,...)`
- Writing to `stdout`: `print()`, `println()`, `printstyled()`
- Writing to `stderr`: `print(stderr,...)`, `println(stderr,...)`, `printstyled(stderr,...)`
- Reading from `stdin`: `readline()`
### Input
The language _Python_ provides a function `input()`:
The _Python_ language provides an `input()` function:
```{.python}
ans = input("Please enter a positive number!")
```
The function prints the prompt, waits for input, and returns the
input as a `string`.
It prints the prompt, waits for input, and returns a `string`.
In Julia, you can implement this function as follows:
@@ -76,12 +75,12 @@ end
**Comments**
- Write instructions are buffered by modern operating systems. With `flush(stdout)`, the buffer is emptied and the write operation is forced to complete immediately.
- `readline()` returns a string ending with a newline `\n`. The function `chomp()` removes a possible line break from the end of a string.
- Write operations are buffered by modern operating systems. `flush(stdout)` empties the buffer and forces the write operation to complete immediately.
- `readline()` returns a string ending with a newline (`\n`). The function `chomp()` removes a trailing line break from the string.
```{julia}
#| eval: false
a = input("Please enter 2 numbers!")
a = input("Please enter two numbers!")
```
```{julia}
#| echo: false
@@ -91,7 +90,7 @@ a = "34 56"
### Processing the Input
> `split(str)` splits a string into "words" and returns an _(array of strings)_:
> `split(str)` splits a string into "words", returning a string array:
```{julia}
av = split(a)
@@ -105,46 +104,33 @@ av = split(a)
v = parse.(Int, av)
```
`parse()` generates an error if the string cannot be parsed as a value of type `T`. You can catch the error with
`try/catch` or use the function `tryparse(T, str)`, which returns `nothing` in such a case - on which you can then
e.g. test with `isnothing()`.
### Reading Individual Keystrokes
- `readline()` and similar functions wait for the input to be completed by pressing the `Enter` key.
- Techniques for reading individual _keystrokes_ can be found here:
- [https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia](https://stackoverflow.com/questions/56888266/how-to-read-keyboard-inputs-at-every-keystroke-in-julia)
- [https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia](https://stackoverflow.com/questions/60954235/how-can-i-test-whether-stdin-has-input-available-in-julia)
`parse()` throws an error if the string cannot be parsed as type `T`. You can catch the error with
`try/catch`, or use `tryparse(T, str)`, which returns `nothing` in such cases. Test the result with `isnothing()`.
## Formatted Output with the `Printf` Macro
Often you want to output numbers or strings with a strict format specification - total length, decimal places, right/left-aligned, etc.
You often need to output numbers or strings with strict formatting: total length, decimal places, alignment, etc.
To this end, the `Printf` package defines the macros `@sprintf` and `@printf`, which work very similarly to the corresponding C functions.
For this purpose, the `Printf` package defines the macros `@sprintf` and `@printf`, which work similarly to the corresponding C functions.
```{julia}
using Printf
x = 123.7876355638734
@printf("Output right-aligned with max. 10 character width and 3 decimal places: x= %10.3f", x)
@printf("Output right-aligned with max. 10 character width and 3 decimal places: x = %10.3f", x)
```
The first argument is a string containing placeholders (here: `%10.3`) for variables to be output; followed by these variables as further arguments.
The first argument is a string containing placeholders (here: `%10.3f`) for the variables, followed by the variables themselves.
Placeholders have the form
Placeholders have the form:
```
%[flags][width][.precision]type
%[flags][width][.precision]type
```
where the entries in square brackets are all optional.
where entries in square brackets are optional.
**Type specifications in placeholders**
@@ -152,11 +138,11 @@ where the entries in square brackets are all optional.
|:--|:------------|
|`%s`| `string`|
|`%i`| `integer`|
|`%o`| `integer octal (base=8)`|
|`%x, %X`| `integer hexadecimal (base=16) with digits 0-9abcdef or 0-9ABCDEF, resp.`|
|`%f`| `floating point number`|
|`%e`| `floating point number, scientific representation`|
|`%g`| `floating point, uses %f or %e depending on value`|
|`%o`| `integer, octal (base 8)`|
|`%x, %X`| `integer, hexadecimal (base 16), digits 0-9a-f or 0-9A-F`|
|`%f`| `floating point`|
|`%e`| `floating point, scientific notation`|
|`%g`| `floating point, %f or %e as appropriate`|
: {.striped .hover}
@@ -165,9 +151,9 @@ where the entries in square brackets are all optional.
| | |
|:----|:-----|
|Plus sign| right-aligned (default)|
|Minus sign| left-aligned|
|Zero| with leading zeros|
|Plus sign| right-aligned (default) |
|Minus sign| left-aligned |
|Zero| adds leading zeros |
: {.striped .hover}
@@ -175,26 +161,26 @@ where the entries in square brackets are all optional.
**Width**
```
Number of minimum characters used (more will be taken if necessary)
Minimum number of characters used (more will be taken if necessary)
```
### Examples:
### Examples
```{julia}
using Printf # Don't forget to load the package!
using Printf # Load the package first
```
```{julia}
@printf("|%s|", "Hello") # string with placeholder for string
```
The vertical bars are not part of the placeholder. They are intended to indicate the boundaries of the output field.
The vertical bars are not part of the placeholder; they indicate the output field boundaries.
```{julia}
@printf("|%10s|", "Hello") # Minimum length, right-aligned
@printf("|%10s|", "Hello") # Minimum length, right-aligned
```
@@ -204,8 +190,8 @@ The vertical bars are not part of the placeholder. They are intended to indicate
```{julia}
@printf("|%3s|", "Hello") # Length specification can be exceeded
# Better a 'badly formatted' table than incorrect values!
@printf("|%3s|", "Hello") # Length specification can be exceeded
# Better a badly formatted table than wrong values!
```
@@ -214,36 +200,34 @@ j = 123
k = 90019001
l = 3342678
@printf("j= %012i, k= %-12i, l = %12i", j, k, l) # 0-flag for leading zeros
@printf("j = %012i, k = %-12i, l = %12i", j, k, l) # 0-flag for leading zeros
```
`@printf` and `@sprintf` can be called like functions or as macros:
`@printf` and `@sprintf` can be called like functions:
```{julia}
@printf("%i %i", 22, j)
```
-- or as macros, i.e., without function parentheses and without comma:
or as macros, i.e., without parentheses or commas:
```{julia}
@printf "%i %i" 22 j
```
`@printf` can take a stream as its first argument.
Otherwise, the argument list consists of
`@printf` can take a stream as its first argument; otherwise, the argument list consists of:
- format string with placeholders
- variables in the order of the placeholders, matching in number and type to the placeholders
- variables matching the placeholders in number and type
```{julia}
@printf(stderr, "First result: %i %s\nSecond result %i",
j, "(estimated)" ,k)
j, "(estimated)", k)
```
The macro `@sprintf` does not print anything but returns the filled formatted string:
The macro `@sprintf` does not print; it returns the formatted string:
```{julia}
@@ -255,12 +239,12 @@ str = @sprintf("x = %10.6f", π );
str
```
### Formatting Floating Point Numbers:
### Formatting Floating-Point Numbers
Meaning of the _precision_ value:
The _precision_ value specifies:
- `%f` and `%e` format: maximum number of decimal places
- `%g` format: maximum number of digits output (integer + decimal places)
- `%f` and `%e` formats: maximum decimal places
- `%g` format: maximum total digits (integer part + decimal places)
```{julia}
@@ -276,34 +260,33 @@ x = 123456.7890123456
```{julia}
@printf("%20.7g %20.4g", x, x) # total 7 and 4 digits respectively
@printf("%20.7g %20.4g", x, x) # 7 and 4 digits total, respectively
```
## File Operations
Files are
Files are handled by:
- opened $\Longrightarrow$ a new _stream_-object is created (in addition to `stdin, stdout, stderr`)
- then this _stream_ can be read from and written to
- closed $\Longrightarrow$ _stream_-object is detached from file
```{.julia}
stream = open(path, mode)
```
- Opening $\Longrightarrow$ creation of a new _stream_ object (in addition to `stdin`, `stdout`, `stderr`)
- Reading from and writing to this _stream_
- Closing $\Longrightarrow$ detachment of the _stream_ object from the file
```
stream = open(path, mode)
```
- path: filename/path
- mode:
```
"r" read, opens at file beginning
"w" write, opens at file beginning (file is created or overwritten)
"a" append, opens to continue writing at file end
```
- path: filename or path
- mode:
```
"r" read, opens at file beginning
"w" write, opens at file beginning (file is created or overwritten)
"a" append, opens to continue writing at file end
```
Let's write a file:
```{julia}
file = open("datei.txt", "w")
file = open("myfile.txt", "w")
```
@@ -324,18 +307,18 @@ close(file)
Let's look at the file:
```{julia}
;cat datei.txt
;cat myfile.txt
```
...and now we open it again for reading:
```{julia}
stream = open("datei.txt", "r")
stream = open("myfile.txt", "r")
```
`readlines(stream)` returns all lines of a text file as a vector of strings.
`readlines(stream)` returns all lines of a text file as a string vector.
`eachline(stream)` returns an iterator over the lines of the file.
`eachline(stream)` returns an iterator over the file lines.
```{julia}
@@ -349,30 +332,30 @@ close(stream)
## Packages for File Formats
For input and output in various file formats, there are Julia packages, e.g.,
Julia packages for various file formats include:
- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Output of formatted tables
- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Input and output of matrices, etc.
- [CSV.jl](https://csv.juliadata.org/stable/) Input and output of "comma-separated values" files, etc.
- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Input and output of Excel files
- [PrettyTables.jl](https://ronisbr.github.io/PrettyTables.jl/stable/) Output formatted tables
- [DelimitedFiles.jl](https://docs.julialang.org/en/v1/stdlib/DelimitedFiles/) Read and write matrices
- [CSV.jl](https://csv.juliadata.org/stable/) Read and write CSV files
- [XLSX.jl](https://felipenoris.github.io/XLSX.jl/stable/tutorial/) Read and write Excel files
and many more...
### DelimitedFiles.jl
This package enables convenient saving/reading of matrices. It provides the functions `writedlm()` and `readdlm()`.
This package offers convenient functions for saving and reading matrices using `writedlm()` and `readdlm()`.
```{julia}
using DelimitedFiles
```
We generate a 200×3 matrix of random numbers
Generate a 200×3 matrix of random numbers:
```{julia}
A = rand(200,3)
```
and save it
and save it:
```{julia}
f = open("data2.txt", "w")
writedlm(f, A)
@@ -387,33 +370,30 @@ The written file starts like this:
```
Reading it back is even simpler:
Reading it back is simple:
```{julia}
B = readdlm("data2.txt")
```
One more point: In Julia, the `do` notation is often used for file handling, see @sec-do.
This uses the fact that `open()` also has methods where the 1st argument is a `function(iostream)`.
This function is then applied to the _stream_ and the stream is automatically closed at the end. The `do` notation allows you to
define this function anonymously after the `do`:
In Julia, the `do` notation is frequently utilized for file handling (see @sec-do). The `open()` function includes methods where the first argument is a `function(iostream)`. This function is applied to the stream, which is automatically closed afterward. The `do` notation allows to define this function anonymously:
```{julia}
open("data2.txt", "w") do io
writedlm(io, A)
end
```
### CSV and DataFrames
- The CSV format is often used to provide tables in a form that can be read not only by MS Excel.
- An example is the weather and climate database _Meteostat_.
- The [DataFrames.jl](https://dataframes.juliadata.org/stable/) package provides functions for convenient handling of tabular data.
- The CSV format provides tables readable by MS Excel and other applications.
- Example: the weather and climate database _Meteostat_.
- The [DataFrames.jl](https://dataframes.juliadata.org/stable/) package handles tabular data conveniently.
```{julia}
using CSV, DataFrames, Downloads
# Weather data from Westerland, see https://dev.meteostat.net/bulk/hourly.html
# Weather data from Westerland (see https://dev.meteostat.net/bulk/hourly.html)
url = "https://bulk.meteostat.net/v2/hourly/10018.csv.gz"
http_response = Downloads.download(url)
@@ -452,8 +432,7 @@ describe(df)
For convenient plotting and handling of date and time formats in the weather table,
we load two helper packages:
For convenient plotting and date/time handling, we load two packages:
```{julia}
using StatsPlots, Dates
@@ -480,7 +459,7 @@ df[!, :datetime] = DateTime.(df.Column1) .+ Hour.(df.Column2);
@df df plot(:datetime, :Column3)
```
And now to the plot:
The resulting plot:
```{julia}
@df df plot(:datetime, [:Column9, :Column6, :Column3],