The `Julia` programming language with a design that makes it well suited as a supplement for the learning of calculus, as this collection of notes is intended to illustrate.
Julia can be used through the internet for free using the [mybinder.org](https://mybinder.org) service. This link: [launch binder](https://mybinder.org/v2/gh/CalculusWithJulia/CwJScratchPad.git/master) will take you to website that allows this.
Just click on the `CalcululsWithJulia.ipynb` file after launching Binder by clicking on the badge. Binder provides the Jupyter interface.
These notes are written as Pluto HTML pages. Pluto is a notebook like alternative to Jupyter which is designed for interactive Julia usage using a *reactive model*. The HTML pages
an be downloaded and run as notebooks within Pluto. (They can also be run through binder, but that will be a disappointing experience due to limitations imposed by binder.)
Pluto will automatically handle the package management for add-on packages, though `Pluto` itself must be installed. In a terminal session, the following commands will install `Pluto`:
Installation happens once. Then each new *session*, `Pluto` must be loaded and run:
```julia; eval=false
using Pluto
Pluto.run()
```
`Pluto` notebooks run in a web browser, the above command will open a landing page in the default browser.
----
Here are some `Julia` usages to create calculus objects.
The `Julia` packages loaded below are all loaded when the `CalculusWithJulia` package is loaded.
A `Julia` package is loaded with the `using` command:
```julia;
using LinearAlgebra
```
The `LinearAlgebra` package comes with a `Julia` installation. Other packages can be added. Something like:
```julia; eval=false
using Pkg
Pkg.add("SomePackageName")
```
These notes have an accompanying package, `CalculusWithJulia`, that when installed, as above, also installs most of the necessary packages to perform the examples.
Packages need only be installed once, but they must be loaded into *each* session for which they will be used.
```julia;
using CalculusWithJulia
```
Packages can also be loaded through `import PackageName`. Importing does not add the exported objects of a function into the namespace, so is used when there are possible name collisions.
## Types
Objects in `Julia` are "typed." Common numeric types are `Float64`, `Int64` for floating point numbers and integers. Less used here are types like `Rational{Int64}`, specifying rational numbers with a numerator and denominator as `Int64`; or `Complex{Float64}`, specifying a comlex number with floating point components. Julia also has `BigFloat` and `BigInt` for arbitrary precision types. Typically, operations use "promotion" to ensure the combination of types is appropriate. Other useful types are `Function`, an abstract type describing functions; `Bool` for true and false values; `Sym` for symbolic values (through `SymPy`); and `Vector{Float64}` for vectors with floating point components.
For the most part the type will not be so important, but it is useful to know that for some function calls the type of the argument will decide what method ultimately gets called. (This allows symbolic types to interact with Julia functions in an idiomatic manner.)
## Functions
### Definition
Functions can be defined four basic ways:
* one statement functions follow traditional mathematics notation:
We see in this notebook the use of `let` blocks, which is not typical with `Pluto`. As `Pluto` is reactive -- meaning changes in a variable propagate automatically to variables which reference the changed one -- a variable can only be used *once* per notebook at the top level. The `let` block, like a function body, introduces a separate scope for the binding so `Pluto` doesn't incorporate the binding in its reactive model. This is necessary as we have more than one function named `f`. This is unlike `begin` blocks, which are quite typical in `Pluto`. The `begin` blocks allow one or more commands to occur in a cell, as the design of `Pluto` is one object per cell.
* multi-statement functions are defined with the `function` keyword. The `end` statement ends the definition. The last evaluated command is returned. There is no need for explicit `return` statement, though it can be useful for control flow.
```julia;
function g(x)
a = sin(x)^2
a + a^2 + a^3
end
```
* Anonymous functions, useful for example, as arguments to other functions or as return values, are defined using an arrow, `->`, as follows:
```julia
fn = x -> sin(2x)
fn(pi/2)
```
In the following, the defined function, `Derivative`, returns an anonymously defined function that uses a `Julia` package, loaded with `CalculusWithJulia`, to take a derivative:
```julia;
Derivatve(f::Function) = x -> ForwardDiff.derivative(f, x) # ForwardDiff is loaded in CalculusWithJulia
```
(The `D` function of `CalculusWithJulia` implements something similar.)
* Anonymous function may also be created using the `function` keyword.
For mathematical functions $f: R^n \rightarrow R^m$ when $n$ or $m$ is bigger than 1 we have:
* When $n =1$ and $m > 1$ we use a "vector" for the return value
Some functions need to pass in a container of values, for this the last definition is useful to expand the values. Splatting takes a container and treats the values like individual arguments.
Alternatively, indexing can be used directly, as in:
When a function has multiple arguments, yet the value passed in is a container holding the arguments, splatting is used to expand the arguments, as is done in the definition `F(v) = F(v...)`, above.
### Multiple dispatch
`Julia` can have many methods for a single generic function. (E.g., it can have many different implementations of addiion when the `+` sign is encountered.)
The *type*s of the arguments and the number of arguments are used for dispatch.
Here the number of arguments is used:
```julia;
Area(w, h) = w * h # area of rectangle
Area(w) = Area(w, w) # area of square using area of rectangle defintion
```
Calling `Area(5)` will call `Area(5,5)` which will return `5*5`.
takes advantage of multiple dispatch to allow either a vector argument or individual arguments.
Type parameters can be used to restrict the type of arguments that are permitted. The `Derivative(f::Function)` definition illustrates how the `Derivative` function, defined above, is restricted to `Function` objects.
### Keyword arguments
Optional arguments may be specified with keywords, when the function is defined to use them. Keywords are separated from positional arguments using a semicolon, `;`:
```julia;
circle(x; r=1) = sqrt(r^2 - x^2)
circle(0.5), circle(0.5, r=10)
```
The main (but not sole) use of keyword arguments will be with plotting, where various plot attribute are passed as `key=value` pairs.
## Symbolic objects
The add-on `SymPy` package allows for symbolic expressions to be used. Symbolic values are defined with `@syms`, as below.
Symbolic expressions flow through `Julia` functions symbolically
```julia;
sin(x)^2 + cos(x)^2
```
Numbers are symbolic once `SymPy` interacts with them:
```julia;
x - x + 1 # 1 is now symbolic
```
The number `PI` is a symbolic `pi`.
```julia;
sin(PI), sin(pi)
```
Use `Sym` to create symbolic numbers, `N` to find a `Julia` number from a symbolic number:
```julia;
1 / Sym(2)
```
```julia;
N(PI)
```
Many generic `Julia` functions will work with symbolic objects through multiple dispatch (e.g., `sin`, `cos`, ...). Sympy functions that are not in `Julia` can be accessed through the `sympy` object using dot-call notation:
```julia;
sympy.harmonic(10)
```
Some Sympy methods belong to the object and a called via the pattern `object.method(...)`. This too is the case using SymPy with `Julia`. For example:
* Tuples. These are objects grouped together using parentheses. They need not be of the same type
```julia;
x1 = (1, "two", 3.0)
```
Tuples are useful for programming. For example, they are uesd to return multiple values from a function.
* Vectors. These are objects of the same type (typically) grouped together using square brackets, values separated by commas:
```julia;
x2 = [1, 2, 3.0] # 3.0 makes theses all floating point
```
Unlike tuples, the expected arithmatic from Linear Algebra is implemented for vectors.
* Matrices. Like vectors, combine values of the same type, only they are 2-dimensional. Use spaces to separate values along a row; semicolons to separate rows:
```julia;
x3 = [1 2 3; 4 5 6; 7 8 9]
```
* Row vectors. A vector is 1 dimensional, though it may be identified as a column of two dimensional matrix. A row vector is a two-dimensional matrix with a single row:
```julia;
x4 = [1 2 3.0]
```
These have *indexing* using square brackets:
```julia;
x1[1], x2[2], x3[3]
```
Matrices are usually indexed by row and column:
```julia;
x3[1,2] # row one column two
```
For vectors and matrices - but not tuples, as they are immutable - indexing can be used to change a value in the container:
```julia;
x2[1], x3[1,1] = 2, 2
```
Vectors and matrices are arrays. As hinted above, arrays have mathematical operations, such as addition and subtraction, defined for them. Tuples do not.
Destructuring is an alternative to indexing to get at the entries in certain containers:
List comprehensions are similar, but are useful as they perform the iteration and collect the values:
```julia;
[i^2 for i in [1,2,3]]
```
Comprehesions can also be used to make matrices
```julia;
[1/(i+j) for i in 1:3, j in 1:4]
```
(The three rows are for `i=1`, then `i=2`, and finally for `i=3`.)
Comprehensions apply an *expression* to each entry in a container through iteration. Applying a function to each entry of a container can be facilitated by:
* Broadcasting. Using `.` before an operation instructs `Julia` to match up sizes (possibly extending to do so) and then apply the operation element by element:
```julia;
xs = [1,2,3]
sin.(xs) # sin(1), sin(2), sin(3)
```
This example pairs off the value in `bases` and `xs`:
This should be contrasted to the case when both `xs` and `ys` are (column) vectors, as then they pair off (and here cause a dimension mismatch as they have different lengths):
Many different computer languages implement `map`, broadcasting is less common. `Julia`'s use of the dot syntax to indicate broadcasting is reminiscent of MATLAB, but is quite different.
The following commands use the `Plots` package. The `Plots` package expects a choice of backend. We will use `gr` unless, but other can be substituted by calling an appropriate command, suchas `pyplot()` or `plotly()`.
The `plotly` backend and `gr` backends are available by default. The `plotly` backend is has some interactivity, `gr` is for static plots. The `pyplot` package is used for certain surface plots, when `gr` can not be used.
The time to first plot can be lengthy! This can be removed by creating a custom `Julia` image, but that is not introductory level stuff. As well, standalone plotting packages offer quicker first plots, but the simplicity of `Plots` is preferred. Subsequent plots are not so time consuming, as the initial time is spent compiling functions so their re-use is speedy.
* Using `plot_parametric`. If the curve is described as a function of `t` with a vector output, then the `CalculusWithJulia` package provides `plot_parametric` to produce a plot:
```julia;
r(t) = exp(t/2pi) * [cos(t), sin(t)]
plot_parametric(0..2pi, r)
```
The low-level approach doesn't quite work as easily as desired:
An arrow in 2D can be plotted with the `quiver` command. We show the `arrow(p, v)` (or `arrow!(p,v)` function) from the `CalculusWithJulia` package, which has an easier syntax (`arrow!(p, v)`, where `p` is a point indicating the placement of the tail, and `v` the vector to represent):
There are numeric and symbolic approaches to derivatives. For the numeric approach we use the `ForwardDiff` package, which performs automatic differentiation.
Numerically, the `ForwardDiff.derivative(f, x)` function call will find the derivative of the function `f` at the point `x`:
```julia;
ForwardDiff.derivative(sin, pi/3) - cos(pi/3)
```
The `CalculusWithJulia` package overides the `'` (`adjoint`) syntax for functions to provide a derivative which takes a function and returns a function, so its usage is familiar
There is no direct partial derivative function provided by `ForwardDiff`, rather we use the result of the `ForwardDiff.gradient` function, which finds the partial derivatives for each variable. To use this, the function must be defined in terms of a point or vector.
As seen, the `ForwardDiff.gradient` function finds the gradient at a point. In `CalculusWithJulia`, the gradient is extended to return a function when called with no additional arguments:
The Jacobian of a function $f:R^n \rightarrow R^m$ is a $m\times n$ matrix of partial derivatives. Numerically, `ForwardDiff.jacobian` can find the Jacobian of a function at a point:
As the Jacobian can be identified as the matrix with rows given by the transpose of the gradient of the component, it can be computed directly, but it is more difficult:
Numerically, the divergence can be computed from the Jacobian by adding the diagonal elements. This is a numerically inefficient, as the other partial derivates must be found and discarded, but this is generally not an issue for these notes. The following uses `tr` (the trace from the `LinearAlgebra` package) to find the sum of a diagonal.
The curl can be computed from the off-diagonal elements of the Jacobian. The calculation follows the formula. The `CalculusWithJulia` package provides `curl` to compute this:
Two and three dimensional integrals over box-like regions are computed numerically with the `hcubature` function from the `HCubature` package. If the box is $[x_1, y_1]\times[x_2,y_2]\times\cdots\times[x_n,y_n]$ then the limits are specified through tuples of the form $(x_1,x_2,\dots,x_n)$ and $(y_1,y_2,\dots,y_n)$.
The box-like region requirement means a change of variables may be necessary. For example, to integrate over the region $x^2 + y^2 \leq 1; x \geq 0$, polar coordinates can be used with $(r,\theta)$ in $[0,1]\times[-\pi/2,\pi/2]$. When changing variables, the Jacobian enters into the formula, through
$$~
\iint_{G(S)} f(\vec{x}) dV = \iint_S (f \circ G)(\vec{u}) |\det(J_G)(\vec{u})| dU.
Symbolically, there is no real difference from a 1-dimensional integral. Let $\phi = 1/\|r\|$ and integrate the gradient field over one turn of the helix $\vec{r}(t) = \langle \cos(t), \sin(t), t\rangle$.
The surface integral for a parameterized surface involves a surface element $\|\partial\Phi/\partial{u} \times \partial\Phi/\partial{v}\|$. This can be computed numerically with:
```julia;
Phi(u,v) = [u*cos(v), u*sin(v), u]
Phi(v) = Phi(v...)
function SE(Phi, pt)
J = ForwardDiff.jacobian(Phi, pt)
J[:,1] × J[:,2]
end
norm(SE(Phi, [1,2]))
```
To find the surface integral ($f=1$) for this surface over $[0,1] \times [0,2\pi]$, we have: