HSG-MCS-HS21_Julia/Problemsets/PS01_Basics.ipynb

1584 lines
125 KiB
Plaintext
Raw Normal View History

2021-11-15 20:14:51 +00:00
{
"cells": [
{
"cell_type": "markdown",
"source": [
"# Basic Julia Tutorial"
],
"metadata": {
"collapsed": true
}
},
{
"cell_type": "markdown",
"source": [
"# Running/Installing Julia\n",
"\n",
"This is a notebook. To run in you need Julia and jupyter or nteract (see below).\n",
"\n",
"1. To run Julia without a local installation, use (for instance) [CoCalc](https://cocalc.com).\n",
"\n",
"2. To install Julia on your machine, [download and install it](https://julialang.org/downloads/). \n",
"\n",
"3. You may also want to use [VS Code with the Julia extension](https://github.com/julia-vscode/julia-vscode) IDE. See also the [julia-vscode.org](https://www.julia-vscode.org/) for more information.\n",
"\n",
"4. To run notebooks with either jupyter or nteract from your local installation, see [IJulia](https://github.com/JuliaLang/IJulia.jl) for instructions. See also below for some hints.\n",
"\n",
"5. As an alternative to jupyter/nteract you can also run notebooks in VS Code (see above).\n",
"\n",
"\n",
"\n",
"## More Details on Installing jupyter and nteract\n",
"\n",
"1. If you want to use nteract do as follows: install IJulia, but do *not* call on `notebook()` to avoid the automatic Python installation. Then install nteract.\n",
"\n",
"2. After installing IJulia and issuing the command `notebook()` a new local Python installation will be made - unless IJulia finds an existing installation.\n",
"\n",
"3. If you already have a Python installation, run `ENV[\"JUPYTER\"] = \"C:\\\\Miniconda3\\\\Scripts\\\\jupyter.exe\"` (change the path as needed) before you install IJulia. The best is perhaps to add this to your startup.jl file (~/.julia/config/startup.jl, for instance, C:\\Users\\yourusername\\.julia\\config\\startup.jl if you are on Windows). You can test whether it works by running ```run(`$(ENV[\"JUPYTER\"]) --version`)``` from the Julia REPL.\n",
"\n",
"4. On Windows, it helps to allow the Python installer to add python to the system path."
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Documentation and Help\n",
"\n",
"1. Cheat sheet at [QuantEcon](https://cheatsheets.quantecon.org/julia-cheatsheet.html)\n",
"2. [Wiki book](https://en.wikibooks.org/wiki/Introducing_Julia)\n",
"3. [Short tutorials](https://techytok.com/from-zero-to-julia/) \n",
"4. [ThinkJulia](https://benlauwens.github.io/ThinkJulia.jl/latest/book.html) is a free on-line book\n",
"5. The [official Julia on-line manual](https://docs.julialang.org)\n",
"6. Discussion lists are found at\n",
" * https://discourse.julialang.org/\n",
" * https://stackoverflow.com/questions/tagged/julia-lang\n",
" * https://www.reddit.com/r/Julia/\n",
" * https://gitter.im/JuliaLang/julia\n",
"7. In Julia, do ```? cos``` to get help with the cos function "
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# About Notebooks\n",
"\n",
"This cell is a \"Markdown\" cell. This is meant for comments and documentation, not computations.\n",
"\n",
"You can change a cell to \"Code\" or \"Markdown\" in the menu.\n",
"\n",
"Markdown cells can handle LaTeX. An example: $\\alpha = \\beta/2$. A Markdown cell can also contain some *formatting*, like lists of this kind\n",
"\n",
"1. To insert a new cell, use the menu. \n",
"\n",
"2. The next cell is \"Code\". You can run it. Text after a # sign is treated as a comment.\n",
"\n",
"3. The subsequent cell shows how to get help on a command."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 41,
"source": [
"a = 2 #this is a comment\n",
" #run this cell by using the menu, or by Shift+Enter"
],
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2"
]
},
"metadata": {},
"execution_count": 41
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 42,
"source": [
"? cos #to get help on the cos() function"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"search: \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22m \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22mh \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22md \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22mc \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22mpi a\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22m a\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22mh a\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22md sin\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22m sin\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22md sin\u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22m\u001b[0m\u001b[1ms\u001b[22mpi \u001b[0m\u001b[1mc\u001b[22m\u001b[0m\u001b[1mo\u001b[22mn\u001b[0m\u001b[1ms\u001b[22mt\n",
"\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/latex": [
"\\begin{verbatim}\n",
"cos(x)\n",
"\\end{verbatim}\n",
"Compute cosine of \\texttt{x}, where \\texttt{x} is in radians.\n",
"\n",
"See also [\\texttt{cosd}], [\\texttt{cospi}], [\\texttt{sincos}], [\\texttt{cis}].\n",
"\n",
"\\rule{\\textwidth}{1pt}\n",
"\\begin{verbatim}\n",
"cos(A::AbstractMatrix)\n",
"\\end{verbatim}\n",
"Compute the matrix cosine of a square matrix \\texttt{A}.\n",
"\n",
"If \\texttt{A} is symmetric or Hermitian, its eigendecomposition (\\href{@ref}{\\texttt{eigen}}) is used to compute the cosine. Otherwise, the cosine is determined by calling \\href{@ref}{\\texttt{exp}}.\n",
"\n",
"\\section{Examples}\n",
"\\begin{verbatim}\n",
"julia> cos(fill(1.0, (2,2)))\n",
"2×2 Matrix{Float64}:\n",
" 0.291927 -0.708073\n",
" -0.708073 0.291927\n",
"\\end{verbatim}\n"
],
"text/markdown": [
"```\n",
"cos(x)\n",
"```\n",
"\n",
"Compute cosine of `x`, where `x` is in radians.\n",
"\n",
"See also [`cosd`], [`cospi`], [`sincos`], [`cis`].\n",
"\n",
"---\n",
"\n",
"```\n",
"cos(A::AbstractMatrix)\n",
"```\n",
"\n",
"Compute the matrix cosine of a square matrix `A`.\n",
"\n",
"If `A` is symmetric or Hermitian, its eigendecomposition ([`eigen`](@ref)) is used to compute the cosine. Otherwise, the cosine is determined by calling [`exp`](@ref).\n",
"\n",
"# Examples\n",
"\n",
"```jldoctest\n",
"julia> cos(fill(1.0, (2,2)))\n",
"2×2 Matrix{Float64}:\n",
" 0.291927 -0.708073\n",
" -0.708073 0.291927\n",
"```\n"
],
"text/plain": [
"\u001b[36m cos(x)\u001b[39m\n",
"\n",
" Compute cosine of \u001b[36mx\u001b[39m, where \u001b[36mx\u001b[39m is in radians.\n",
"\n",
" See also [\u001b[36mcosd\u001b[39m], [\u001b[36mcospi\u001b[39m], [\u001b[36msincos\u001b[39m], [\u001b[36mcis\u001b[39m].\n",
"\n",
" ────────────────────────────────────────────────────────────────────────────\n",
"\n",
"\u001b[36m cos(A::AbstractMatrix)\u001b[39m\n",
"\n",
" Compute the matrix cosine of a square matrix \u001b[36mA\u001b[39m.\n",
"\n",
" If \u001b[36mA\u001b[39m is symmetric or Hermitian, its eigendecomposition (\u001b[36meigen\u001b[39m) is used to\n",
" compute the cosine. Otherwise, the cosine is determined by calling \u001b[36mexp\u001b[39m.\n",
"\n",
"\u001b[1m Examples\u001b[22m\n",
"\u001b[1m ≡≡≡≡≡≡≡≡≡≡\u001b[22m\n",
"\n",
"\u001b[36m julia> cos(fill(1.0, (2,2)))\u001b[39m\n",
"\u001b[36m 2×2 Matrix{Float64}:\u001b[39m\n",
"\u001b[36m 0.291927 -0.708073\u001b[39m\n",
"\u001b[36m -0.708073 0.291927\u001b[39m"
]
},
"metadata": {},
"execution_count": 42
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Load Packages and Extra Functions\n",
"\n",
"There are many packages for Julia, for instance, for plotting or statistical methods (see [JuliaHub](https://juliahub.com/) for a list). To install a package, you do either \n",
"\n",
"1. (works everywhere) run `import Pkg` and then `Pkg.add(\"Packagename\")`\n",
"\n",
"2. (works in the Julia console, REPL) enter the \"package manager mode\" by typing `]`, then run `add PackageName`. You leave the package manager mode by ctrl-c or backspace.\n",
"\n",
"Once a package is installed, you can use it by running\n",
"\n",
"```\n",
"using PackageName\n",
"```"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 77,
"source": [
"using Printf\n",
"\n",
"include(\"jlFiles/printmat.jl\") #just a function for prettier matrix printing"
],
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"printyellow (generic function with 1 method)"
]
},
"metadata": {},
"execution_count": 77
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 78,
"source": [
"using Plots #this loads the Plots package\n",
"\n",
"#pyplot(size=(600,400)) #choice of plotting backend\n",
"gr(size=(480,320))\n",
"default(fmt = :svg) #try :png or :svg"
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Scalars and Matrices\n",
"\n"
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### Create a Scalar and a Matrix"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 45,
"source": [
"q = 1 #create a scalar\n",
"Q = [ 1 2 3; #create 2x3 matrix\n",
" 4 5 6 ] \n",
"println(\"q is a scalar. To print, use println() or printlnPs()\")\n",
"println(q)\n",
"\n",
"println(\"\\nQ is a matrix. To print, use display() or printmat()\")\n",
"printmat(Q) \n",
"display(Q) #case sensitive (q and Q are different)\n",
" #the \\n adds a line break"
],
"outputs": [
{
"output_type": "display_data",
"data": {
"text/plain": [
"2×3 Matrix{Int64}:\n",
" 1 2 3\n",
" 4 5 6"
]
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
"q is a scalar. To print, use println() or printlnPs()\n",
"1\n",
"\n",
"Q is a matrix. To print, use display() or printmat()\n",
" 1 2 3 \n",
" 4 5 6 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### Picking Out Parts of a Matrix"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 46,
"source": [
"println(\"\\n\",\"element [1,2] of Q: \", #commands continue on\n",
" Q[1,2]) #the next line (until finished)\n",
"\n",
"println(\"\\ncolumns 2 and 3 of Q: \")\n",
"printmat(Q[:,2:3])\n",
"\n",
"println(\"\\nline 1 of Q (as a vector): \")\n",
"printmat(Q[1,:])"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"element [1,2] of Q: 2\n",
"\n",
"columns 2 and 3 of Q: \n",
" 2 3 \n",
" 5 6 \n",
"\n",
"\n",
"line 1 of Q (as a vector): \n",
" 1 \n",
" 2 \n",
" 3 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"Create a 2x2 matrix A\n",
"\n",
"```\n",
"10 10\n",
"21 22\n",
"```\n",
"\n",
"Print it\n",
"\n",
"Change the second row to `[1 2]`. Print again."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 80,
"source": [
"A = [10 10;\n",
" 21 22]\n",
"\n",
"printmat(A)\n",
"\n",
"A[2,:] = [1 2]\n",
"\n",
"printmat(A)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 10 10 \n",
" 21 22 \n",
"\n",
" 10 10 \n",
" 1 2 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### Basic Linear Algebra\n",
"\n",
"The syntax for linear algebra is similar to the standard text book approach. For instance, \n",
"* `Q'Q` (or `Q'*Q`) multiplies the transpose ($Q'$) with the matrix ($Q$)\n",
"* `A*B` does matrix multiplication\n",
"* `100*Q` multiplies each element of the matrix ($Q$) by 100. (You can also do `100Q`.)\n",
"\n",
"However, to add a scalar to each element of a matrix, use `100 .+ Q`. Notice the dot."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 79,
"source": [
"println(\"Q:\")\n",
"printmat(Q)\n",
"\n",
"println(\"transpose of Q:\")\n",
"printmat(Q')\n",
"\n",
"println(\"Q'Q:\")\n",
"printmat(Q'Q)\n",
"\n",
"println(\"scalar * matrix:\")\n",
"printmat(100*Q)\n",
"\n",
"println(\"scalar .+ matrix:\") #notice the dot\n",
"printmat(100 .+ Q)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Q:\n",
" 1 2 3 \n",
" 4 5 6 \n",
"\n",
"transpose of Q:\n",
" 1 4 \n",
" 2 5 \n",
" 3 6 \n",
"\n",
"Q'Q:\n",
" 17 22 27 \n",
" 22 29 36 \n",
" 27 36 45 \n",
"\n",
"scalar * matrix:\n",
" 100 200 300 \n",
" 400 500 600 \n",
"\n",
"scalar .+ matrix:\n",
" 101 102 103 \n",
" 104 105 106 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Consider the system of linear equations\n",
"\n",
"$\n",
"Ax = q\n",
"$, \n",
"\n",
"where \n",
"$ \n",
"q = \\begin{bmatrix} 1 \\\\2 \\end{bmatrix}\n",
"$\n",
"\n",
"You could solve it as\n",
"$\n",
"x = A^{-1}q\n",
"$\n",
"\n",
"\n",
"Solve (numrically) for the vector $x$. Hint: `inv()` Then check that $Ax$ indeed equals $q$"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 81,
"source": [
"q = [1, 2]\n",
"\n",
"printmat(q)\n",
"\n",
"x = inv(A)q\n",
"\n",
"printmat(x)\n",
"\n",
"printmat(A*x)\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 1 \n",
" 2 \n",
"\n",
" -1.800\n",
" 1.900\n",
"\n",
" 1.000\n",
" 2.000\n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 83,
"source": [
"x_alt = A\\q"
],
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"2-element Vector{Float64}:\n",
" -1.8\n",
" 1.9"
]
},
"metadata": {},
"execution_count": 83
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### Creating a Sequence and a Vector"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 50,
"source": [
"θ = 1:10:21 #a range, type \\theta[TAB] to get this symbol\n",
"println(\"\\n\",\"θ is a sequence: \",θ)\n",
"\n",
"ρ = collect(θ) #make the sequence into a vector, \\rho[TAB]\n",
"println(\"\\n\",\"ρ is a vector: \")\n",
"printmat(ρ)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"\n",
"θ is a sequence: 1:10:21\n",
"\n",
"ρ is a vector: \n",
" 1 \n",
" 11 \n",
" 21 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Create a sequence $\\alpha$ which starts at 0 and ends at 1, taking 11 steps. (Hint: you can also use `range()`)"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 84,
"source": [
"α = 0:0.1:1\n",
"\n",
"α2 = range(0, 1, 11)\n",
"\n",
"printmat(α)\n",
"println(α2)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 0.000\n",
" 0.100\n",
" 0.200\n",
" 0.300\n",
" 0.400\n",
" 0.500\n",
" 0.600\n",
" 0.700\n",
" 0.800\n",
" 0.900\n",
" 1.000\n",
"\n",
"0.0:0.1:1.0\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Comparing Things\n",
"\n",
"To see if the scalar z <= 0, do \n",
"```\n",
"vv = z <= 0\n",
"```\n",
"to get a single output (true or false).\n",
"\n",
"Instead, if x is an array, do \n",
"```\n",
"vv = x .<= 0 #notice the dot.\n",
"```\n",
"to get an array of outputs (same dimension as x)"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 52,
"source": [
"x = [-1.5,-1.0,-0.5,0,0.5] #this is a vector\n",
"\n",
"println(\"x values: \")\n",
"printmat(x)\n",
"\n",
"vv = -1 .< x .<= 0 #true for x values (-1,0], vv is a vector\n",
"println(\"true if x is in (-1,0]: \")\n",
"printmat(vv)\n",
"\n",
"x2 = x[vv] #x values for which vv==true\n",
"println(\"x values that are in (-1,0]: \")\n",
"printmat(x2)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"x values: \n",
" -1.500\n",
" -1.000\n",
" -0.500\n",
" 0.000\n",
" 0.500\n",
"\n",
"true if x is in (-1,0]: \n",
" 0 \n",
" 0 \n",
" 1 \n",
" 1 \n",
" 0 \n",
"\n",
"x values that are in (-1,0]: \n",
" -0.500\n",
" 0.000\n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Which elements of $\\alpha$ are (weakly) between 0.6 and 0.99?"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 53,
"source": [
"# printmat(α)\n",
"\n",
"vv = 0.6 .< α .< 0.99\n",
"\n",
"# printmat(vv)\n",
"printmat(α[vv])\n"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 0.700\n",
" 0.800\n",
" 0.900\n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Finding Things\n",
"\n",
"can be done by, for instance, `findfirst()`, `findall()` and `indexin()`. \n",
"\n",
"Instead, if you just need to check if the number `z` is in an array (or any collection) `x`, then use `in(z,x)`."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 54,
"source": [
"x = [-1.5,-1.0,-0.5,0,0.5] #this is a vector\n",
"\n",
"println(\"x values: \")\n",
"printmat(x)\n",
"\n",
"v1 = findfirst(x.==0)\n",
"println(\"(first) index v in x such x[v]==0: \",v1)\n",
"\n",
"v2 = findall(x.>=0)\n",
"println(\"\\nall indices v in x such x[v]>=0: \")\n",
"printmat(v2)\n",
"\n",
"y = [-1.0,0]\n",
"v3 = indexin(y,x)\n",
"println(\"\\nindices in x so that x[v] equals the vector y=$y: \")\n",
"printmat(v3)\n",
"\n",
"v4 = in(0,x)\n",
"println(\"\\ntesting if 0 is in x: \",v4)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"x values: \n",
" -1.500\n",
" -1.000\n",
" -0.500\n",
" 0.000\n",
" 0.500\n",
"\n",
"(first) index v in x such x[v]==0: 4\n",
"\n",
"all indices v in x such x[v]>=0: \n",
" 4 \n",
" 5 \n",
"\n",
"\n",
"indices in x so that x[v] equals the vector y=[-1.0, 0.0]: \n",
" 2 \n",
" 4 \n",
"\n",
"\n",
"testing if 0 is in x: true\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# if-else\n",
"\n",
"allows you to run different comman ddepending on a condition which you specify.\n",
"\n",
"(extra) There are also other (more compact) possibilities for `if-else` case\n",
"\n",
"1. `y = ifelse(z <= 2,z,2)` or \n",
"2. `z <= 2 ? y = z : y = 2`\n",
"(In this partcular case, `y=minimum(z,2)` also works.)\n",
"\n",
"You can also insert an `ifelse` command."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 55,
"source": [
"z = 1.05\n",
"\n",
"if z <= 2 #(a) if true, run the next command (y=z) and then jump to end\n",
" y = z\n",
"else #(b) if (a) is false, do this instead\n",
" y = 2\n",
"end\n",
"\n",
"#y = ifelse(z <= 2,z,2) #these two versions also work\n",
"#z <= 2 ? y = z : y = 2\n",
"\n",
"println(y)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1.05\n"
]
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 56,
"source": [
"if z < 1 #(a) if true, run the next command (y=1) and then jump to end\n",
" y = 1\n",
"elseif 1 <= z <= 2 #(b) if (a) is false, try this instead \n",
" y = z\n",
"else #(c) if also (b) is false, do this\n",
" y = 2\n",
"end\n",
"\n",
"println(y)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"1.05\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"\n",
"Use `if-else` to calculate the tax paid by someone with an income of $X$. The tax schedule is progressive so the first 100 of the income pays 40% tax, while income above 100 has a marginal tax rate of 0.6 (that is, $X-100$ pays 60% if $X>100)$. What is the total tax paid and the average tax rate.\n",
"Report the results for an income of 150."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 85,
"source": [
"X = 150\n",
"\n",
"if X > 100\n",
" tax = 100 * 0.4 + (X - 100) * 0.6\n",
"else\n",
" tax = X * 0.4\n",
"end\n",
"\n",
"println(\"The tax is: \", tax)\n",
"println(\"Avarage tax is: \", tax / X * 100)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"The tax is: 70.0\n",
"Avarage tax is: 46.666666666666664\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Loops\n",
"\n",
"The are two types of loops: \"for loops\" and \"while loops\". \n",
"\n",
"The *for loop* is best when you know how many times you want to loop (for instance, over all $m$ rows in a matrix). \n",
"\n",
"The *while loop* is best when you want to keep looping until something happens, for instance, that $x_0$ and $x_1$ get really close.\n",
"\n",
"The default behaviour in *IJulia*, *inside functions* and at the *REPL* promt is that assignments of `x` inside the loop overwrites `x` defined before the loop. To get the same behavior in scripts, you need to add `global x` somewhere inside the loop.\n",
"\n",
"To make sure that the `y` calculated inside the loop does not affect `y` outside the loop, add `local y`.\n",
"\n",
"A variable (here `z2`) that does not exist before the loop is local to the loop."
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### A Simple \"for loop\"\n",
"\n",
"The \"for loop\" in the next cell makes 3 iterations and changes a global $x$ variable."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 58,
"source": [
"x = 0\n",
"y = -999\n",
"for i = 3:3:9 #or `i in 3:3:9`, or `v=[3,6,9]; i in v`\n",
" #global x #only needed in script\n",
" local y #don't overwrite y outside loop\n",
" x += i #adding i to the \"old\" x\n",
" y = i\n",
" z2 = -998 #notice: z2 has not been used before \n",
" println(\"i=$i, x=$x and z2=$z2\") #$x prints the value of x\n",
"end\n",
"\n",
"println(\"\\nAfter loop: x=$x and y=$y\")\n",
"#println(z2) #does not work: z2 is local to the loop"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"i=3, x=3 and z2=-998\n",
"i=6, x=9 and z2=-998\n",
"i=9, x=18 and z2=-998\n",
"\n",
"After loop: x=18 and y=-999\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"You have the following financial data\n",
"\n",
"```\n",
"P = [100;108;109] #price series, after dividends\n",
"D = [0;2;0] #dividends\n",
"```\n",
"\n",
"For each $t$, calculate the returns\n",
"\n",
"$\n",
"R_t = (P_t+D_t)/P_{t-1} - 1\n",
"$,\n",
"\n",
"by using a loop."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 91,
"source": [
"P = [100;108;109]\n",
"D = [0;2;0]\n",
"\n",
"for t = 1:3\n",
" if t > 1\n",
" x = (P[t] + D[t]) / P[t - 1] - 1\n",
" else\n",
" x = \"n/a\"\n",
" end\n",
" println(\"returns are: $x\")\n",
"end"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"returns are: n/a\n",
"returns are: 0.10000000000000009\n",
"returns are: 0.0092592592592593\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"### A Double \"for loop\"\n",
"\n",
"An example of a nested for for loop\n",
"\n",
"```\n",
"for j = 1:n, i = 1:m\n",
" #do something\n",
"end\n",
"```\n",
"\n",
"If you prefer, could also write a longer version to do the same thing\n",
"```\n",
"for j = 1:n \n",
" for i = 1:m\n",
" #do something\n",
" end \n",
"end\n",
"```\n",
"\n",
"The next cell uses a double loop to fill a matrix. "
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 60,
"source": [
"(m,n) = (4,3) #same as m=4;n=3\n",
"x = fill(-999,(m,n)) #to put results in, initialized as -999\n",
"for i = 1:m, j = 1:n\n",
" x[i,j] = 10*i + j\n",
"end\n",
"\n",
"println(\"new x matrix: \\n\")\n",
"printmat(x)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"new x matrix: \n",
"\n",
" 11 12 13 \n",
" 21 22 23 \n",
" 31 32 33 \n",
" 41 42 43 \n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## A Simple \"while loop\"\n",
"\n",
"The \"while loop\" in the next cell iterates until two variables ($x_0$ and $x_1$) get close.\n",
"\n",
"The background to the example is that we want to solve a function $f(x)=x^2$ for the $x$ value that makes $f(x)=2$. The Newton-Raphson algorithm starts with a value $x_0$ and updates it to\n",
"$\n",
"x_1 = x_0 + (2-f(x_0))/f'(x_0)\n",
"$\n",
"where $f'(x_0)$ is the derivative of $f()$ evaluated at $x_0$. The algorithm iterates until $x_0$ and $x_1$ are close. Clearly, we are trying to find the square root of 2."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 61,
"source": [
"println(\"Solving x^2 = 2 with Newton-Raphson:\\n\")\n",
"\n",
"x₀ = Inf #x\\_0[TAB]\n",
"x₁ = 10\n",
"\n",
"while abs(x₁-x₀) > 0.001 #keep going until they get similar\n",
" #global x₀, x₁ #only needed in script\n",
" local y, dy #don't overwrite any y,dy outside loop\n",
" x₀ = x₁ #initial guess is taken from old guess\n",
" y = x₀^2 #value of function\n",
" dy = 2*x₀ #derivative of function\n",
" x₁ = x₀ + (2 - y)/dy #updating the guess, Newton-Raphson\n",
" printlnPs(x₀,\" is changed to \",x₁)\n",
"end\n",
"\n",
"printlnPs(\"\\nThe result should be close to \",sqrt(2))"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Solving x^2 = 2 with Newton-Raphson:\n",
"\n",
" 10 is changed to 5.100\n",
" 5.100 is changed to 2.746\n",
" 2.746 is changed to 1.737\n",
" 1.737 is changed to 1.444\n",
" 1.444 is changed to 1.415\n",
" 1.415 is changed to 1.414\n",
"\n",
"The result should be close to 1.414\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Start at `x=1` and create a while loop that multiplies the previous $x$ by 1.1.(That is, you earn a 10% return each year.) Continue while `x<2`. Print the iterations (iteration number, `x`). So, how many years did it take to double the investment?"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 92,
"source": [
"x = 1\n",
"while x < 2\n",
" x = x * 1.1\n",
" printlnPs(x)\n",
"end"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
" 1.100\n",
" 1.210\n",
" 1.331\n",
" 1.464\n",
" 1.611\n",
" 1.772\n",
" 1.949\n",
" 2.144\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# A Simple Function\n",
"\n",
"The next cell defines a new function, `fn1()`. It takes a scalar input (`x`) and returns a scalar output (`y`).\n",
"\n",
"If you instead use a vector as the input, then the computation fails. (The reason is that you cannot do x^2 on a vector. You could on a square matrix, though.)\n",
"\n",
"However, using the \"dot\" syntax\n",
"```\n",
"y = fn1.(x)\n",
"```\n",
"gives an array as output where element `y[i,j] = fn1(x[i,j])`."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 63,
"source": [
"function fn1(x) #define a new function \n",
" y = (x-1.1)^2 - 0.5\n",
" return y\n",
"end"
],
"outputs": [
{
"output_type": "execute_result",
"data": {
"text/plain": [
"fn1 (generic function with 1 method)"
]
},
"metadata": {},
"execution_count": 63
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 64,
"source": [
"y = fn1(1.5)\n",
"printlnPs(\"result from fn1(1.5): \",y)\n",
"\n",
"x = [1;1.5]\n",
"#y = fn1(x) #would give an error \n",
"y = fn1.(x) #calling on the function, dot. to do for each element in x\n",
"printlnPs(\"\\nresult from fn1.(x): \")\n",
"printmat(y)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"result from fn1(1.5): -0.340\n",
"\n",
"result from fn1.(x): \n",
" -0.490\n",
" -0.340\n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Write a function to calculate \n",
"$B =\\exp{(-my)}$, \n",
"where $B$ is the price of a bond and $m$ is the time to maturity (measured in years) and $y$ is the (continously compounded) interest rate.\n",
"\n",
"If $y=0.103$ and $m=0.5$, what is $B$?"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 96,
"source": [
"using Base\n",
"\n",
"function test(m, y)\n",
" return exp(-m * y)\n",
"end\n",
"\n",
"BondPrice(m, y) = exp(-m * y)\n",
"\n",
"B = test(0.5, 0.103)\n",
"printlnPs(\"B = $B\")\n",
"printlnPs(BondPrice(0.5, 0.103))"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"B = 0.9498036499621996\n",
" 0.950\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# A First Plot\n",
"\n",
"With the Plots package you create a a simple plot like this:\n",
"\n",
"1. Plot two curve by using the `plot([x1 x2],[y1 y2])` command\n",
"2. Configure curves by `linecolor =`, `linestyle =` etc\n",
"2. Add titles and labels by `title = `, `xlabel = `, etc\n",
"\n",
"Notice: the *first plot is slow*."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 66,
"source": [
"x = -3:6/99:6 \n",
"\n",
"p1 = plot( [x x],[fn1.(x) cos.(x)],\n",
" linecolor = [:red :blue],\n",
" linestyle = [:solid :dash],\n",
" linewidth = [2 1],\n",
" label = [\"fn1()\" \"cos\"],\n",
" title = \"My Results\",\n",
" xlabel = \"x\",\n",
" ylabel = \"my output value\" )\n",
"display(p1) #not needed in notebook, but useful in script"
],
"outputs": [
{
"output_type": "display_data",
"data": {
"image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"480\" height=\"320\" viewBox=\"0 0 1920 1280\">\n<defs>\n <clipPath id=\"clip300\">\n <rect x=\"0\" y=\"0\" width=\"1920\" height=\"1280\"/>\n </clipPath>\n</defs>\n<path clip-path=\"url(#clip300)\" d=\"\nM0 1280 L1920 1280 L1920 0 L0 0 Z\n \" fill=\"#ffffff\" fill-rule=\"evenodd\" fill-opacity=\"1\"/>\n<defs>\n <clipPath id=\"clip301\">\n <rect x=\"384\" y=\"0\" width=\"1345\" height=\"1280\"/>\n </clipPath>\n</defs>\n<path clip-path=\"url(#clip300)\" d=\"\nM199.164 1106.38 L1872.76 1106.38 L1872.76 123.472 L199.164 123.472 Z\n \" fill=\"#ffffff\" fill-rule=\"evenodd\" fill-opacity=\"1\"/>\n<defs>\n <clipPath id=\"clip302\">\n <rect x=\"199\" y=\"123\" width=\"1675\" height=\"984\"/>\n </clipPath>\n</defs>\n<polyline clip-path=\"url(#clip302)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 422.551,1106.38 422.551,123.472 \n \"/>\n<polyline clip-path=\"url(#clip302)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 774.594,1106.38 774.594,123.472 \n \"/>\n<polyline clip-path=\"url(#clip302)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1126.64,1106.38 1126.64,123.472 \n \"/>\n<polyline clip-path=\"url(#clip302)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1478.68,1106.38 1478.68,123.472 \n \"/>\n<polyline clip-path=\"url(#clip302)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1830.72,1106.38 1830.72,123.472 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 199.164,1106.38 1872.76,1106.38 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 422.551,1106.38 422.551,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 774.594,1106.38 774.594,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1126.64,1106.38 1126.64,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1478.68,1106.38 1478.68,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip300)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1830.72,1106.38 1830.72,1087.48 \n \"/>\n<path clip-path=\"url(#clip300)\" d=\"M392.493 1146.38 L422.169 1146.38 L422.169 1150.32 L392.493 1150.32 L392.493 1146.38 Z\" fill=\"#000000\" fill-rule=\"evenodd\" fill-opacity=\"1\" /><path clip-path=\"url(#clip300)\" d=\"M436.289 1159.28 L452.609 1159.28 L452.609 1163.21 L430.664 1163.21 L430.664 1159.28 Q433.326 1156.52 437.91 1151.89 Q442.516 1147.24 443.697 1145.9 Q445.942 1143.37 446.822 1141.64 Q447.725 1139.88 447.725 1138.19 Q447.725 1135.43 445.78 1133.7 Q443.859 1131.96 440.757 1131.96 Q438.558 1131.96 436.104 1132.73 Q433.674 1133.49 430.896 1135.04 L430.896 1130.32 Q433.72 1129.18 436.174 1128.61 Q438.627 1128.03 440.664 1128.03 Q446.035 1128.03 449.229 1130.71 Q452.424 1133.4 452.424 1137.89 Q452.424 1140.02 451.613 1141.94 Q450.826 1143.84 448.72 1146.43 Q448.141 1147.1 445.039 1150.32 Q441.937 1153.51 436.289 1159.28 Z\" fill=\"#000000\" fill-rule=\"evenodd\" fill-opacity=\"1\"
},
"metadata": {}
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Task\n",
"\n",
"Consider different interest rates in the interval (-0.05,0.1). Plot the prices of 3-month and 10-year bonds as functions of the interest rate."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 101,
"source": [
"\n",
"x = range(-0.05,stop=0.1,length=100) \n",
"printmat(x)\n",
"\n",
"p2 = plot( [x x], [BondPrice.(0.33, x) BondPrice.(10, x)],\n",
" label = [\"y 0.3\" \"y 10\"],\n",
" xlabel = \"interest rate\",\n",
" ylabel = \"bond price\",\n",
" linecolor = [:red :blue],\n",
" linestyle = [:solid :dot],\n",
" linewidth = [2 2] )\n",
"display(p2)"
],
"outputs": [
{
"output_type": "display_data",
"data": {
"image/svg+xml": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"480\" height=\"320\" viewBox=\"0 0 1920 1280\">\n<defs>\n <clipPath id=\"clip500\">\n <rect x=\"0\" y=\"0\" width=\"1920\" height=\"1280\"/>\n </clipPath>\n</defs>\n<path clip-path=\"url(#clip500)\" d=\"\nM0 1280 L1920 1280 L1920 0 L0 0 Z\n \" fill=\"#ffffff\" fill-rule=\"evenodd\" fill-opacity=\"1\"/>\n<defs>\n <clipPath id=\"clip501\">\n <rect x=\"384\" y=\"0\" width=\"1345\" height=\"1280\"/>\n </clipPath>\n</defs>\n<path clip-path=\"url(#clip500)\" d=\"\nM244.742 1106.38 L1872.76 1106.38 L1872.76 47.2441 L244.742 47.2441 Z\n \" fill=\"#ffffff\" fill-rule=\"evenodd\" fill-opacity=\"1\"/>\n<defs>\n <clipPath id=\"clip502\">\n <rect x=\"244\" y=\"47\" width=\"1629\" height=\"1060\"/>\n </clipPath>\n</defs>\n<polyline clip-path=\"url(#clip502)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 495.6,1106.38 495.6,47.2441 \n \"/>\n<polyline clip-path=\"url(#clip502)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 802.772,1106.38 802.772,47.2441 \n \"/>\n<polyline clip-path=\"url(#clip502)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1109.94,1106.38 1109.94,47.2441 \n \"/>\n<polyline clip-path=\"url(#clip502)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1417.12,1106.38 1417.12,47.2441 \n \"/>\n<polyline clip-path=\"url(#clip502)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:2; stroke-opacity:0.1; fill:none\" points=\"\n 1724.29,1106.38 1724.29,47.2441 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 244.742,1106.38 1872.76,1106.38 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 495.6,1106.38 495.6,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 802.772,1106.38 802.772,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1109.94,1106.38 1109.94,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1417.12,1106.38 1417.12,1087.48 \n \"/>\n<polyline clip-path=\"url(#clip500)\" style=\"stroke:#000000; stroke-linecap:butt; stroke-linejoin:round; stroke-width:4; stroke-opacity:1; fill:none\" points=\"\n 1724.29,1106.38 1724.29,1087.48 \n \"/>\n<path clip-path=\"url(#clip500)\" d=\"M427.371 1146.38 L457.046 1146.38 L457.046 1150.32 L427.371 1150.32 L427.371 1146.38 Z\" fill=\"#000000\" fill-rule=\"evenodd\" fill-opacity=\"1\" /><path clip-path=\"url(#clip500)\" d=\"M477.139 1131.73 Q473.528 1131.73 471.699 1135.3 Q469.894 1138.84 469.894 1145.97 Q469.894 1153.07 471.699 1156.64 Q473.528 1160.18 477.139 1160.18 Q480.773 1160.18 482.579 1156.64 Q484.407 1153.07 484.407 1145.97 Q484.407 1138.84 482.579 1135.3 Q480.773 1131.73 477.139 1131.73 M477.139 1128.03 Q482.949 1128.03 486.005 1132.63 Q489.083 1137.22 489.083 1145.97 Q489.083 1154.69 486.005 1159.3 Q482.949 1163.88 477.139 1163.88 Q471.329 1163.88 468.25 1159.3 Q465.195 1154.69 465.195 1145.97 Q465.195 1137.22 468.25 1132.63 Q471.329 1128.03 477.139 1128.03 Z\" fill=\"#000000\" fill-rule=\"evenodd\" fill-opacity=\"1\" /><path clip-path=\"url(#clip500)\" d=\"M497.301 1157.33 L502.185 1157.33
},
"metadata": {}
},
{
"output_type": "stream",
"name": "stdout",
"text": [
" -0.050\n",
" -0.048\n",
" -0.047\n",
" -0.045\n",
" -0.044\n",
" -0.042\n",
" -0.041\n",
" -0.039\n",
" -0.038\n",
" -0.036\n",
" -0.035\n",
" -0.033\n",
" -0.032\n",
" -0.030\n",
" -0.029\n",
" -0.027\n",
" -0.026\n",
" -0.024\n",
" -0.023\n",
" -0.021\n",
" -0.020\n",
" -0.018\n",
" -0.017\n",
" -0.015\n",
" -0.014\n",
" -0.012\n",
" -0.011\n",
" -0.009\n",
" -0.008\n",
" -0.006\n",
" -0.005\n",
" -0.003\n",
" -0.002\n",
" 0.000\n",
" 0.002\n",
" 0.003\n",
" 0.005\n",
" 0.006\n",
" 0.008\n",
" 0.009\n",
" 0.011\n",
" 0.012\n",
" 0.014\n",
" 0.015\n",
" 0.017\n",
" 0.018\n",
" 0.020\n",
" 0.021\n",
" 0.023\n",
" 0.024\n",
" 0.026\n",
" 0.027\n",
" 0.029\n",
" 0.030\n",
" 0.032\n",
" 0.033\n",
" 0.035\n",
" 0.036\n",
" 0.038\n",
" 0.039\n",
" 0.041\n",
" 0.042\n",
" 0.044\n",
" 0.045\n",
" 0.047\n",
" 0.048\n",
" 0.050\n",
" 0.052\n",
" 0.053\n",
" 0.055\n",
" 0.056\n",
" 0.058\n",
" 0.059\n",
" 0.061\n",
" 0.062\n",
" 0.064\n",
" 0.065\n",
" 0.067\n",
" 0.068\n",
" 0.070\n",
" 0.071\n",
" 0.073\n",
" 0.074\n",
" 0.076\n",
" 0.077\n",
" 0.079\n",
" 0.080\n",
" 0.082\n",
" 0.083\n",
" 0.085\n",
" 0.086\n",
" 0.088\n",
" 0.089\n",
" 0.091\n",
" 0.092\n",
" 0.094\n",
" 0.095\n",
" 0.097\n",
" 0.098\n",
" 0.100\n",
"\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Types: Integers, Floats, Bools and Others\n",
"\n",
"Julia has many different types of variables: signed integers (like 2 or -5), floating point numbers (2.0 and -5.1), bools (false/true), bitarrays (similar to bools, but with more efficient use of memory), strings (\"hello\"), Dates (2017-04-23) and many more types."
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Integers and Floats"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 68,
"source": [
"a = 2 #integer, Int (Int64 on most machines)\n",
"b = 2.0 #floating point, (Float64 on most machines)\n",
"A = [1,2]\n",
"B = [1.0,2.0]\n",
"\n",
"println(\"Finding the type of a, b, A and B:\")\n",
"println(typeof(a),\" \",typeof(b),\" \",typeof(A),\" \",typeof(B))"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Finding the type of a, b, A and B:\n",
"Int64 Float64 Vector{Int64} Vector{Float64}\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Bools and BitArrays\n",
"\n",
"Bools are \"true\" or \"false\". BitArrays are (more memory efficient) versions of this."
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 69,
"source": [
"c = 2 > 1.1\n",
"C = A .> 1.5 #A is an array, so C is too\n",
"\n",
"println(\"Finding the type of c and C:\")\n",
"println(typeof(c),\" \",typeof(C))"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"Finding the type of c and C:\n",
"Bool BitVector\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Calculations with Mixed Types\n",
"\n",
"A calculation like \"integer\" + \"float\" works and the type of the result will be a float (the more flexible type). Similarly, \"bool\" + \"integer\" will give an integer. These promotion rules make it easy to have mixed types in calculations, and also provide a simple way of converting a variable from one type to another. (There are also an explicit convert() function that might be quicker.)"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 70,
"source": [
"println(1+2.0) #integer + Float\n",
"println((1>0) + 2) #bool + integer"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"3.0\n",
"3\n"
]
}
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [],
"outputs": [],
"metadata": {}
}
],
"metadata": {
"@webio": {
"lastCommId": null,
"lastKernelId": null
},
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Julia 1.7.0-rc1",
"language": "julia",
"name": "julia-1.7"
},
"language_info": {
"file_extension": ".jl",
"name": "julia",
"mimetype": "application/julia",
"version": "1.7.0"
}
},
"nbformat": 4,
"nbformat_minor": 1
}