-
Notifications
You must be signed in to change notification settings - Fork 5
/
01-basics.jmd
564 lines (405 loc) · 11.9 KB
/
01-basics.jmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
---
title : Getting started with Julia
author : Michiel Stock, Bram De Jaegher, Daan Van Hauwermeiren
date: December 2019
---
# Basic computing
Let's get started with the basics. Some mathematical operations,
```julia; term=true
1 + 2 # adding integers
```
```julia; term=true
1.0 + 2.0 # adding floats
```
```julia; term=true
2 / 4 # standard division
```
```julia; term=true
div(2, 4) # Computes 2/4 truncated to an integer
2 ÷ 4
```
```julia; term=true
7 % 3 # get the remainder of the integer division
```
```julia; term=true
35 \ 7 # inverse division
```
```julia; term=true
1 // 3 # fractions
```
```julia; term=true
1//2 + 1//4
```
```julia; term=true
'c' # characters (unicode)
```
```julia; term=true
:symbol # symbols, mostly used for macros
```
variable assignment,
```julia; term=true
x = 2
```
```julia; term=true
τ = 1 / 37 # unicode variable names are allowed
```
unicode! In most Julia editing environments, unicode math symbols can be typed when starting with a "\ and hitting [TAB].
```julia
# type \alpha and <TAB>
```
Operators are overrated.
```julia
5x # This works
```
But strings are quite essential,
```julia
mystery = "life, the universe and everything"
```
and string interpolation is performed with `$`.
```julia
println("The answer to $mystery is $(3*2*7)")
```
repetitions of strings can be done using the operators `*` and `^`.
This use of `*` and `^` makes sense by analogy with multiplication and exponentiation. Just as `4^3` is equivalent to `4*4*4`, we expect `"Spam"^3` to be the same as `"Spam"*"Spam"*"Spam"`, and it is.
```julia
breakfast = "eggs"
abetterbreakfast = "SPAM"
println(breakfast * abetterbreakfast)
println(breakfast * abetterbreakfast^3 * breakfast)
```
Lots of handy ´String`-operations are available in the standard library of Julia:
```julia
uppercase("This feels like shouting.")
```
```julia
findfirst("a", "banana")
```
```julia
findfirst("na", "banana")
```
```julia
findnext("na", "banana", 4)
```
Unlike `Strings´, a `Char` value represents a single character and is surrounded by single quotes.
```julia
'x'
```
The operator `∈` (\in TAB) is a boolean operator that takes a character and a string and returns true if the first appears in the second:
```julia
'a' ∈ "banana"
```
> **Question**: Check the behaviour of the relational operators on strings.
```julia; eval=false
"apples" == "pears"
```
```julia; eval=false
"apples" < "pears"
```
```julia; eval=false
"apples" < "Pears"
```
All binary arithmetic and bitwise operators have an updating version that assigns the result of the operation back into the left operand. The updating version of the binary operator is formed by placing a, `=`, immediately after the operator.
```julia; term=true
x += 2 # inplace update of x
x += 2 # inplace update of x
```
Similarly to Matlab, when using the REPL, Julia will print the result of every statement by default. To suppress this behavious, just end the statement with a semicolon.
```julia; term=true
a = 10; # not printed
```
```julia; term=true
a = 20
```
# Boolean operators
From zero to one.
```julia; term = true
# Boolean operators
!true
```
```julia; term=true
!false
```
```julia; term=true
1 == 1
```
```julia; term=true
2 == 1
```
```julia; term=true
1 != 1
```
```julia; term=true
2 != 1
```
```julia; term=true
1 < 10
```
```julia; term=true
1 > 10
```
```julia; term=true
2 <= 2
```
```julia; term=true
2 >= 2
```
```julia; term=true
# Comparisons can be chained
1 < 2 < 3
```
```julia; term=true
2 < 3 < 2
```
```julia; term=true
# Logical operators
true && true
true || false
```
Likewise, we have the Boolean logic operators `&&` (AND), `||` (OR) and `⊻` (XOR, exclusive or).
```julia; term=true
true && true
```
```julia; term=true
true && false
```
```julia; term=true
true || false
```
```julia; term=true
false || false
```
```julia; term=true
true ⊻ false
```
```julia; term=true
true ⊻ true
```
> **Question**: predict the outcomes of the following statements.
```julia; eval=false
x, y = true, false
(x || y) && !(y || y)
```
```julia; term=true
(x ⊻ y) && (!x ⊻ !y)
```
```julia; term=true
(x || y) ⊻ (x && y)
```
# Control flow
The `if`, `else`, `elseif`-statement is instrumental to any programming language,
```julia
if 4 > 3
println("A")
elseif 3 > 4
println("B")
else
println("C")
end
```
Julia allows for some very condense control flow structures.
```julia
y = condition ? valueiftrue : valueiffalse
```
> **Assignment** Complete the clip function: $\max(0, \min(1, x))$ for a given $x$, without making use of the functions `min` and `max`.
```julia; eval=false
x = 2.0
clip(x) = ...
```
# Looping
```julia
characters = ["Harry", "Ron", "Hermione"]
for char in characters
println("Character $char")
end
for (i, char) in enumerate(characters)
println("$i. $char")
end
pets = ["Hedwig", "Pig", "Crookhanks"]
for (char, pet) in zip(characters, pets)
println("$char has $pet as a pet")
end
```
Strings can also be looped
```julia
getme = "a shrubbery"
for letter ∈ getme
println("$letter")
end
```
```julia;eval = false
n = 1675767616;
while n > 1
println(n)
if n % 2 == 0
global n = div(n, 2)
else
global n = 3n + 1
end
end
```
(Note: [they got closer to cracking this one](https://www.quantamagazine.org/mathematician-terence-tao-and-the-collatz-conjecture-20191211/?mc_cid=a3adbffb9f&mc_eid=41ed2fca13).)
# Functions
Julia puts the fun in functions. User-defined functions can be declared as follows,
```julia
function square(x)
result = x * x
return result
end
```
```julia; term=true
square(2)
```
```julia; term=true
square(2.0)
```
```julia; term=true
square("ni") # the multiplication of strings is defined as a concatenation
```
A more condensed version of of `square(x)`.
```julia
s(x) = x * x
```
Passing an array to a function that takes a single element as argument takes a special syntax. By putting a `.` before the brackets, the function is executed on all the elements of the Array. More on this in **Part2: collections**.
```julia; eval = false
s([1, 2, 3, 4, 5]) # Multiplication is not defined for Arrays
```
```julia
s.([1, 2, 3, 4, 5]) # This is an elements-wise execution of s()
```
Keyword arguments are defined using a semicolon in the back signature and a default value can be assigned. "Keywords" assigned before the semicolon are default values but their keywords are not ignored.
```julia
safelog(x, offset=0.1; base=10) = log(x + offset) / log(base)
```
```julia; term=true
safelog(0)
```
```julia; term=true
safelog(0, 0.01)
```
```julia; term=true
safelog(0, 0.01, base=2)
```
When functions have a variable number of arguments, one can use the *slurping* `...` operator to denote a variable number of arguments. The argument will be treated as a collection. For example
```julia; term=true
function mymean(X...)
m = zero(first(X)) # ensures to be the same type as x
# m = 0.0 # alternative that is less tidy
for x in X
m += x
end
return m / length(X)
end
mymean(1, 3, 5)
```
```julia; term=true
mymean(1, 3, 5, 7)
```
Similarly, the *splatting* operator can be used to split a collection into its individual elements.
```julia
c = [1.0, 3.0, 5.0];
mymean(c...)
```
When unsure of what a function does, the documentation can be viewed by adding a "?" in front of the function.
```julia
# type ?sort and hit <ENTER>
```
For a lot of standard Julia functions a in-place version is defined. In-place means that the function changes one of the input arguments of the function. As an example, `sort()` sorts and returns the array passed as argument, it does not change the original array. In contrast, `sort!()` is the inplace version of sort and directly sorts the array passed as argument.
```julia
my_unsorted_list = [4, 5, 9, 7, 1, 9]
sort(my_unsorted_list)
```
```julia; term=true
my_unsorted_list
```
```julia; term=true
sort!(my_unsorted_list)
my_unsorted_list
```
Specific functions can be generated if you have more information on the input type.
This is called multiple dispatch.
The `::` operator attaches type annotations to expressions and variables.
How does the documentation for the function square look like after you executed the cell below?
```julia
function square(x::Float64)
println("using function with floats")
result = x * x
return result
end
println(square(4))
println(square(4.))
```
More about types in the next section !
# Macros
Macros provide a method to include generated code in the final body of a program. It is a way of generating a new output expression, given an unevaluated input expression. When your Julia program runs, it first parses and evaluates the macro, and the processed code produced by the macro is eventually evaluated like an ordinary expression.
Some nifty basic macros are `@time` and `@show`. `@time` prints the cpu time and memory allocations of an expression.
```julia
@time square(10)
```
The `@show` macro is often useful for debugging purposes. It displays both the expression to be evaluated and its result, finally returning the value of the result.
```julia
@show 1 + 1
```
# Plotting
Quite essential for scientific programming is the visualisation of the results. `Plots` is the Julia package that handles a lot of the visualisation. `rand(10)`, returns an array of 10 random floats between 0 and 1.
```julia
using Plots
plot(1:10, rand(10), label="first")
plot!(1:10, rand(10), label="second") # adding to current figure using plot!
scatter!([1:10], randn(10), label="scatter")
xlabel!("x")
ylabel!("f(x)")
title!("My pretty Julia plot")
```
```julia
# notice the use of a symbol as an argument !
plot(0:0.1:10, x -> sin(x) / x, xlabel="x", ylabel="sin(x)/x", color=:red, marker=:square, legend=:none)
```
```julia
contour(-5:0.1:5, -10:0.1:10, (x, y) -> 3x^2-4y^2 + x*y/6)
```
# Exercises
## 1
Write a function named `rightjustify` that takes a string named `s` as a parameter and prints the string with enough leading spaces so that the last letter of the string is in column 70 of the display.
Use string concatenation and repetition. Also, Julia provides a built-in function called `length`. Check what it does!
```julia;eval = false
function rightjustify()
end
```
## 2
1. Write a function `printgrid` that draws a grid like the following:
```julia;eval = false
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
| | |
| | |
| | |
| | |
+ - - - - + - - - - +
```
2. Write a function that draws a similar grid with four rows and four columns.
Tips:
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.
```julia;eval = false
function printgrid()
end
```
## 3
The function `time` returns the current Greenwich Mean Time in seconds since "the epoch", which is an arbitrary time used as a reference point. On UNIX systems, the epoch is 1 January 1970.
Write a script that reads the current time and converts it to a time of day in hours, minutes, and seconds, plus the number of days since the epoch.
```julia;eval = false
```
## 4
Fermat’s Last Theorem says that there are no positive integers $a$, $b$, and $c$ such that
$a^n + b^n = c^n$
for any value of $n$ greater than 2.
1. Write a function named `checkfermat` that takes four parameters ($a$, $b$, $c$ and $n$) and checks to see if Fermat’s theorem holds. If $n$ is greater than 2 and $a^n + b^n == c^n$ the program should print, "Holy smokes, Fermat was wrong!" Otherwise the program should print, "No, that doesn’t work."
2. Write a function that prompts the user to input values for $a$, $b$, $c$ and $n$, converts them to integers, and uses checkfermat to check whether they violate Fermat’s theorem. Tip: check the functions `readline` and `parse`
3. Can you write the code so that the functions in 4.1 and 4.2 have the same name?
```julia;eval = false
```