x = 11
The assignment operator = binds a name to a piece of data.
To see the data content:
@show expression to show the expression and its resultprintln(data): good old print function.@printf: C-like formatted output.; at the end will suppress inline output.An integer (64 bit)
A (64-bit) floating-point number
A 32-bit floating-point number. less accurate but calculates faster. Often used in GPU computing.
Complex number
Unicode names are supported. For example, \alpha<tab>
Strings (Text) are surrounded by double quotes.
Characters are surrounded by single quotes.
Fractions (rational numbers)
Constants will emit a warning if you try to change it after its creation
Print content to the terminal
@show will print x = val
Types of the data
typeof(x) = Int64
typeof(y) = Float32
typeof(c) = Char
typeof(s) = String
typeof(z) = Complex{Int64}
typeof(1 // 2) = Rational{Int64}
convert(T,x) converts x to type T
There is also Type(x)
Converts numbers to floating numbers
Julia supports basic arithmetic operations and essential math functions by default.
Multiple assignment
Addition
Subtraction
Multiplication
Division
Fraction
integer division: \div<tab>, the same as div(a, b)
Modulus
Power
Returns a boolean value (true or false)
Chained comparisons are supported
Approximation operator \approx<TAB> for floating point number equivalence
The same as
How to type π : \pi<TAB>
More precise
More precise
\sqrt<TAB>
Natural log
Common log
Natural exponent
expm1(x) is more accurate that exp(x) - 1 when x is very close to zero.
A string is a sequence of characters.
" ... " for one line strings.str1*str2*... to concatenate stringsstring(str1, str2, ...) to convert the data (if needed) and make a string.^ to repeat a string: str^3 to repeat str three times.[idx] to access an individual character.$ to insert (or interpolate) a value into a string.Although string(x, y) looks less streamlined, it is generally faster than interpolation $ or concatenation *.
A character is different from a string
How to insert contents into a string
String interpolation $
String concatenation *
begin … end squashes multiple expressions into one.let … end is similar to a begin block but variables inside will be discarded outside the block.a1 and a2 are available after begin block ends
x, y, z are NOT available after let block ends
elseif and else blocks are optional. if and end are mandatory.if blocks return a value. Capturing the value is optional.if blocks are “leaky”, i.e. they do not introduce a local scope. (The same as Python)if blocks. Using other types (e.g. Int) will generate an error.cond ? T:F
A no-branching alternative. All the arguments are evaluated first in ifelse(cond, tvalue, fvalue).
&& (logical and) and || (logical or) operators support short circuit evaluation.
a && b, the expression b would be evaluated only if a evaluates to true.a || b, the expression b would be evaluated only if a evaluates to false.Short circuit and && evaluates and returns the second argument if the first is true
otherwise it returns false
A if block can return value(s)
"Uh-Oh"
Ternary operator
Repeated evaluations in a code block.
While loop (we will use it to solve stochastic simulations)
For loop (we will use it to solve ODEs)
Loop controls:
break: exit the loop immediately.continue: move on to the predicate immediately.Hailstone sequence (3n+1 problem) in a while loop
77
Summation
How continue and break work
1^2 = 1
2^2 = 4
3^2 = 9
4^2 = 16
6^2 = 36
7^2 = 49
You can use enumerate(seq) to get a pair of index number and the element.
xs[1] = 2
xs[2] = 3
xs[3] = 5
xs[4] = 7
xs[5] = 9
xs[6] = 11
xs[7] = 13
Multiple nested for loops can be combined into a single outer loop, forming the cartesian product of its iterables.
In Julia, a function is an object that maps a tuple of argument values to a return value. Julia docs
Functions could do: - Code reuse and encapsulation. - Specializations of Methods for different data types.
Notes: - Functions are first-class objects and can be passed into a higher-order function. - The arguments are “passed-by-sharing” (Similar to Python). Modifications to mutable argument values (such as Arrays) will be reflected to the caller. - By convention, functions that will update the arguments are named with a bang !. (e.g. sort(arr) vs sort!(arr)) - For element-wise operations, use the broadcast (dot) syntax. e.g. sqrt.(arr) - You can write multiple functions with the same name provided they have distinct parameters. Julia will choose the most appropriate one according to the input.
Main.var"##277".mm
Call the function
And you can also reuse previously-defined functions
Anonymous functions are often used with other functions that take in another function. e.g. map(func, seq)
Use the do block for long anonymous functions.
10-element Vector{Int64}:
2
0
1
0
6
1
0
3
1
2
The same as
Optional (positional) arguments are listed after mandatory ones.
And they are called with func(a, b) or func(a, b, 3)
Keyword arguments are listed after ;. They are called by name rather than order.
And they are called with plot(x, y, width=2) or plot(x, y; width=2)
Using built-in collections is the simplest way to group and organize data.
The values in a immutable collection cannot be updated after its creation, while in a mutable collection can.
The elements in sequential collections are accessed by integer indices, while those in associative collection are accessed by keys.
General rules for sequential collections:
seq[i] or an integer range seq[1:2:end-1].length(seq) returns the total size... passes the inner contents in the collection as positional function arguments.start[:step]:end
A simple range starts from one, and stops at ten, with a step size of two,.
Length of a sequence
Show its content
Explicit range function
Pick an element
Pick elements by a range of indices
Tuples are usually written as
Pick elements You cannot change the elements once its created. (immutable)
Merging multiple tuples using the splat (…) operator
(x, y, z) = (3, 1, 2)
Tuple can return multiple values from a function
[seq...] / collect(seq)
Arrays are the bread and butter for scientific computing, similar to numpy’s ndarrays.
Some useful functions for arrays:
length(A) the number of elements in Andims(A) the number of dimensions of Asize(A) a tuple containing the dimensions of Asize(A,n) the size of A along dimension neachindex(A) an efficient iterator for visiting each position in A1D array (column vector)
np.arange() equivalent
Array with all zeroes
2×5×2 Array{Float64, 3}:
[:, :, 1] =
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
[:, :, 2] =
0.0 0.0 0.0 0.0 0.0
0.0 0.0 0.0 0.0 0.0
Array with all ones
Uninitialized array with the same data type and dims as x
np.zeros_like()
Array of random numbers
Reshape an array
3×4 reshape(::UnitRange{Int64}, 3, 4) with eltype Int64:
1 4 7 10
2 5 8 11
3 6 9 12
Reshape A to an (1D) vector
repeat the array 3x2 times
comprehension for 1D array
2D comprehension for a 2x3 array
casting comprehension result element type to Float64
This is a 1-element tuple containing a vector
How to convert vector to tuple
2D array (matrix) A space is a shorthand for hcat() A semicolon is a shorthand for vcat()
Accessing elements
Accessing a range of elements
Array total length
(Conjugate transpose) Adjoint
Matrix-vector multiplication
Find x for Ax = b, using left division operator /
Flatten A to an (1D) vector
Arrays are mutable (i.e. you can update the contents) objects You should make a copy if you want the original one intact
d[key] accesses values by keysd[key] = value sets a key-value pair for a mutable dictionary.delete!(d, key) deletes the kay (and its partner) from a mutable dictionary.keys(d) returns a series of keysvalues(d) returns a series of valuespairs(d) returns a series of (key => value) pairsmerge(d1, d2, ...) return combinations of several dicts. merge!(d1, d2, ...) combine several dicts and update the first one.get(d, key, default) returns the value stored for the given key, or the given default value if no mapping for the key is present.Namedtuples are tuples with key-value pairs.
How to fill a named tuple elegantly
Dictionaries are mutable mappings of key => value.
Dict{String, String} with 3 entries:
"two" => "dos"
"one" => "uno"
"three" => "tres"
ValueIterator for a Dict{String, String} with 4 entries. Values:
"dos"
"uno"
"tres"
"cinco"
Elements are not ordered
Creating a dict from an array of tuples
Creating a Dict via a generator (similar to comprehensions)
Dict{Int64, Int64} with 10 entries:
5 => 25
4 => 16
6 => 36
7 => 49
2 => 4
10 => 100
9 => 81
8 => 64
3 => 9
1 => 1
Broadcasting turns scalar operations into vector ones.
Element-wise operation
Create a dictionary with a list of keys and a list of values
Dict{Symbol, Int64} with 3 entries:
:a => 1
:b => 2
:c => 3
How to do logspace() in Julia
50-element Vector{Float64}:
0.001
0.0013257113655901094
0.0017575106248547913
0.002329951810515372
0.0030888435964774815
0.004094915062380423
0.005428675439323859
0.0071968567300115215
0.009540954763499945
0.012648552168552958
⋮
104.81131341546852
138.94954943731375
184.20699693267164
244.20530945486522
323.74575428176433
429.1934260128778
568.9866029018299
754.3120063354615
1000.0
Make a 9*9 multiplication table
https://docs.julialang.org/en/v1/manual/types/#Composite-Types
struct or mutable struct
Define a default constructor
Define a method for our custom type
You can overload the same function with different argument types/numbers. Julia will try to find the right function for the argument type(s).
func (generic function with 5 methods)
This notebook was generated using Literate.jl.
Comments
Comments are non-coding parts in the source code. Although the compiler does not read comments, comments are important notes for humans, making the code more readable (hopefully).