edits
This commit is contained in:
@@ -4,6 +4,7 @@ DataFrames = "a93c6f00-e57d-5684-b7b6-d8193f3e46c0"
|
||||
IJulia = "7073ff75-c697-5162-941a-fcdaad2a7d2a"
|
||||
IntervalArithmetic = "d1acc4aa-44c8-5952-acd4-ba5d80a2a253"
|
||||
LaTeXStrings = "b964fa9f-0449-5b57-a5c2-d3ea65f4040f"
|
||||
Latexify = "23fbe1c1-3f47-55db-b15f-69d7ec21a316"
|
||||
Markdown = "d6f4376e-aef5-505a-96c1-9c027394607a"
|
||||
Measures = "442fdcdd-2543-5da2-b0f3-8c86c306513e"
|
||||
Mustache = "ffc61752-8dc7-55ee-8c37-f3e9cdd09e70"
|
||||
|
||||
@@ -42,7 +42,7 @@ For these examples, the domain of both $f(x)$ and $g(x)$ is all real values of $
|
||||
|
||||
In general the range is harder to identify than the domain, and this is the case for these functions too. For $f(x)$ we may know the $\cos$ function is trapped in $[-1,1]$ and it is intuitively clear than all values in that set are possible. The function $h(x)$ would have range $[0,\infty)$. The $s(x)$ function is either $-1$ or $1$, so only has two possible values in its range. What about $g(x)$? It is a parabola that opens upward, so any $y$ values below the $y$ value of its vertex will not appear in the range. In this case, the symmetry indicates that the vertex will be at $(1/2, -1/4)$, so the range is $[-1/4, \infty)$.
|
||||
|
||||
::: {#fig-domain-range layout-nrow=2}
|
||||
::: {#fig-domain-range-1}
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plt = let
|
||||
@@ -70,7 +70,7 @@ plt = let
|
||||
Δy = (y1-y0)/60
|
||||
Δx = (b - a)/75
|
||||
|
||||
plot(; aspect_ratio=:equal, empty_style...)
|
||||
plot(; empty_style...) # aspect_ratio=:equal,
|
||||
plot!([-.25,3.25],[0,0]; axis_style...)
|
||||
plot!([0,0], [min(-2Δy, y0 - Δy), y1 + 4Δy]; axis_style... )
|
||||
|
||||
@@ -83,9 +83,13 @@ plt = let
|
||||
plot!([a, b], [f(a), f(a)]; mark_style...)
|
||||
plot!([a, b], [f(b), f(b)]; mark_style...)
|
||||
end
|
||||
plot
|
||||
plt
|
||||
```
|
||||
|
||||
Figure of the plot of a function over an interval $[a,b]$ highlighting the domain and the range.
|
||||
:::
|
||||
|
||||
::: {#fig-domain-range-2}
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plt = let
|
||||
@@ -124,7 +128,7 @@ plt = let
|
||||
plot!(Shape(Δx*[-1,1,1,-1], [-5, -5,-1,-1]); range_style...)
|
||||
plot!(Shape(Δx*[-1,1,1,-1], [ 5, 5,1,1]); range_style...)
|
||||
end
|
||||
plot
|
||||
plt
|
||||
```
|
||||
|
||||
|
||||
@@ -134,7 +138,7 @@ plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
The top figure shows the domain and range of the function as highlighted intervals. The bottom figure shows that the domain may be a collection of intervals. (In this case the $\sec$ function is not defined at $\pi/2 + k \pi$ for integer $k$) and the range may be a collection of intervals. (In this case, the $\sec$ function never have a value in $(-1,1)$.
|
||||
This figure shows that the domain of a function may be a collection of intervals. (In this case the $\sec$ function is not defined at $\pi/2 + k \pi$ for integer $k$) and the range may be a collection of intervals. (In this case, the $\sec$ function never has a value in $(-1,1)$.
|
||||
:::
|
||||
|
||||
|
||||
@@ -176,7 +180,7 @@ For typical cases like the three above, there isn't really much new to learn.
|
||||
|
||||
|
||||
:::{.callout-note}
|
||||
## Note
|
||||
## The equals sign is used differently between math and Julia
|
||||
The equals sign in `Julia` always indicates either an assignment or a mutation of the object on the left side. The definition of a function above is an *assignment*, in that a function is added (or modified) in a table holding the methods associated with the function's name.
|
||||
|
||||
The equals sign restricts the expressions available on the *left*-hand side to a) a variable name, for assignment; b) mutating an object at an index, as in `xs[1]`; c) mutating a property of a struct; or d) a function assignment following this form `function_name(args...)`.
|
||||
@@ -216,7 +220,10 @@ $$
|
||||
f(x) = 5/9 \cdot (x - 32)
|
||||
$$
|
||||
|
||||
In fact, the graph of a function $f(x)$ is simply defined as the graph of the equation $y=f(x)$. There is a distinction in `Julia` as a command such as
|
||||
In fact, the graph of a function $f(x)$ is simply defined as the graph of the equation $y=f(x)$.
|
||||
|
||||
|
||||
There **is** a distinction in `Julia`. The last command here
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -236,13 +243,65 @@ f(72) ## room temperature
|
||||
will create a function object with a value of `x` determined at a later time - the time the function is called. So the value of `x` defined when the function is created is not important here (as the value of `x` used by `f` is passed in as an argument).
|
||||
|
||||
|
||||
Within `Julia`, we make note of the distinction between a function object versus a function call. In the definition `f(x)=cos(x)`, the variable `f` refers to a function object, whereas the expression `f(pi)` is a function call. This mirrors the math notation where an $f$ is used when properties of a function are being emphasized (such as $f \circ g$ for composition) and $f(x)$ is used when the values related to the function are being emphasized (such as saying "the plot of the equation $y=f(x)$).
|
||||
Within `Julia`, we make note of the distinction between a function object versus a function call. In the definition `f(x)=cos(x)`, the variable `f` refers to a function object, whereas the expression `f(pi)` is a function call, resulting in a value. This mirrors the math notation where an $f$ is used when properties of a function are being emphasized (such as $f \circ g$ for composition) and $f(x)$ is used when the values related to the function are being emphasized (such as saying "the plot of the equation $y=f(x)$).
|
||||
|
||||
|
||||
Distinguishing these three related but different concepts -- equations and expressions, function objects, and function calls -- is important when modeling mathematics on the computer.
|
||||
Distinguishing these related but different concepts --- expressions, equations, values from function calls, and function objects --- is important when modeling mathematics on the computer.
|
||||
|
||||
::: {#fig-kidney}
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plt = let
|
||||
gr()
|
||||
# two kidneys and an arrow
|
||||
ts = range(0, 2pi, 200)
|
||||
a = 1
|
||||
x(t) = 6a*cos(t) + sin(t) - 4a*cos(t)^5
|
||||
y(t) = 4a*sin(t)^3
|
||||
S = Shape(x.(ts), y.(ts))
|
||||
|
||||
y1(t) = 6a*cos(t) -3sin(t) - 4a*cos(t)^5
|
||||
x1(t) = 4a*sin(t)^3
|
||||
|
||||
T = Shape(x1.(ts), y1.(ts))
|
||||
T = Plots.translate(T, 10, 0)
|
||||
|
||||
plot(; empty_style...)
|
||||
plot!(S, fill=(:gray, 0.2), line=(:black, 1))
|
||||
plot!(T, fill=(:gray, 0.2), line=(:black, 1))
|
||||
|
||||
P = (0,0)
|
||||
Q = (10, 0)
|
||||
scatter!([P,Q], marker=(:circle,))
|
||||
|
||||
ts = reverse(range(pi/4+.1, 3pi/4-.1, 100))
|
||||
plot!(5 .+ 5*sqrt(2)*cos.(ts), -5 .+ 5*sqrt(2)*sin.(ts);
|
||||
line=(:black, 1), arrow=true, side=:head)
|
||||
|
||||
|
||||
### Cases
|
||||
annotate!([
|
||||
(P..., text(L"x", :top)),
|
||||
(Q..., text(L"f(x)", :top)),
|
||||
(5, 3, text(L"f", :top)),
|
||||
(0, -6, text("Domain")),
|
||||
(10, -6, text("Range"))
|
||||
])
|
||||
|
||||
end
|
||||
plt
|
||||
```
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
Common illustration of an abstract function mapping a value $x$ in the domain to a value $y=f(x)$ in the range. In `Julia`, the values are named, as with `x`, or computed, as with `f(x)`. The function *object* `f` is like the named arrow, which is the name assigned to a particular mapping.
|
||||
:::
|
||||
|
||||
### Cases, the ternary operator
|
||||
|
||||
|
||||
The definition of $s(x)$ above has two cases:
|
||||
@@ -256,7 +315,7 @@ s(x) =
|
||||
\end{cases}
|
||||
$$
|
||||
|
||||
We learn to read this as: when $x$ is less than $0$, then the answer is $-1$. If $x$ is greater than $0$ the answer is $1.$ Often - but not in this example - there is an "otherwise" case to catch those values of $x$ that are not explicitly mentioned. As there is no such "otherwise" case here, we can see that this function has no definition when $x=0$. This function is often called the "sign" function and is also defined by $\lvert x\rvert/x$. (`Julia`'s `sign` function actually defines `sign(0)` to be `0`.)
|
||||
We learn to read this as: when $x$ is less than $0$, then the answer is $-1$. If $x$ is greater than $0$ the answer is $1.$ Often--but not in this example--there is an "otherwise" case to catch those values of $x$ that are not explicitly mentioned. As there is no such "otherwise" case here, we can see that this function has no definition when $x=0$. This function is often called the "sign" function and is also defined by $\lvert x\rvert/x$. (`Julia`'s `sign` function defines `sign(0)` to be `0`.)
|
||||
|
||||
|
||||
How do we create conditional statements in `Julia`? Programming languages generally have "if-then-else" constructs to handle conditional evaluation. In `Julia`, the following code will handle the above condition:
|
||||
@@ -298,7 +357,7 @@ For example, here is one way to define an absolute value function:
|
||||
abs_val(x) = x >= 0 ? x : -x
|
||||
```
|
||||
|
||||
The condition is `x >= 0` - or is `x` non-negative? If so, the value `x` is used, otherwise `-x` is used.
|
||||
The condition is `x >= 0`--or is `x` non-negative? If so, the value `x` is used, otherwise `-x` is used.
|
||||
|
||||
|
||||
Here is a means to implement a function which takes the larger of `x` or `10`:
|
||||
@@ -311,16 +370,16 @@ bigger_10(x) = x > 10 ? x : 10.0
|
||||
(This could also utilize the `max` function: `f(x) = max(x, 10.0)`.)
|
||||
|
||||
|
||||
Or similarly, a function to represent a cell phone plan where the first $500$ minutes are $20$ dollars and every additional minute is $5$ cents:
|
||||
Or similarly, a function to represent a cell phone plan where the first $5$ Gb of data are $11$ dollars and every additional GB is $3.50$:
|
||||
|
||||
|
||||
```{julia}
|
||||
cellplan(x) = x < 500 ? 20.0 : 20.0 + 0.05 * (x-500)
|
||||
cellplan(x) = x <= 5 ? 11.0 : 11.0 + 3.50 * (x-5)
|
||||
```
|
||||
|
||||
:::{.callout-warning}
|
||||
## Warning
|
||||
Type stability. These last two definitions used `10.0` and `20.0` instead of the integers `10` and `20` for the answer. Why the extra typing? When `Julia` can predict the type of the output from the type of inputs, it can be more efficient. So when possible, we help out and ensure the output is always the same type.
|
||||
Type stability. These last two definitions used `10.0` and `11.0` instead of the integers `10` and `11` for the answer. Why the extra typing? When `Julia` can predict the type of the output from the type of inputs, it can be more efficient. So when possible, we help out and ensure the output is always the same type.
|
||||
|
||||
:::
|
||||
|
||||
@@ -391,7 +450,7 @@ $$
|
||||
f(x) = \left(\frac{g}{k v_0\cos(\theta)} + \tan(\theta) \right) x + \frac{g}{k^2}\ln\left(1 - \frac{k}{v_0\cos(\theta)} x \right)
|
||||
$$
|
||||
|
||||
Here $g$ is the gravitational constant $9.8$ and $v_0$, $\theta$ and $k$ parameters, which we take to be $200$, $45$ degrees and $1/2$ respectively. With these values, the above function can be computed when $x=100$ with:
|
||||
Here $g$ is the gravitational constant $9.8$ and $v_0$, $\theta$, and $k$ parameters, which we take to be $200$, $45$ degrees and $1/2$ respectively. With these values, the above function can be computed when $x=100$ with:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -541,7 +600,12 @@ $$
|
||||
f(x) = m \cdot x + b, \quad g(x) = y_0 + m \cdot (x - x_0).
|
||||
$$
|
||||
|
||||
Both functions use the variable $x$, but there is no confusion, as we learn that this is just a dummy variable to be substituted for and so could have any name. Both also share a variable $m$ for a slope. Where does that value come from? In practice, there is a context that gives an answer. Despite the same name, there is no expectation that the slope will be the same for each function if the context is different. So when parameters are involved, a function involves a rule and a context to give specific values to the parameters. Euler had said initially that functions composed of "the variable quantity and numbers or constant quantities." The term "variable," we still use, but instead of "constant quantities," we use the name "parameters."
|
||||
Both functions use the variable $x$, but there is no confusion, as we
|
||||
learn that this is just a dummy variable to be substituted for and so
|
||||
could have any name. Both also share a variable $m$ for a slope.
|
||||
Where does the value for $m$ come from?
|
||||
|
||||
In practice, there is a context that gives an answer. Despite the same name, there is no expectation that the slope will be the same for each function if the context is different. So when parameters are involved, a function involves a rule and a context to give specific values to the parameters. Euler had said initially that functions composed of "the variable quantity and numbers or constant quantities." The term "variable," we still use, but instead of "constant quantities," we use the name "parameters." In computer language, instead of context, we use the word *scope*.
|
||||
|
||||
|
||||
Something similar is also true with `Julia`. Consider the example of writing a function to model a linear equation with slope $m=2$ and $y$-intercept $3$. A typical means to do this would be to define constants, and then use the familiar formula:
|
||||
@@ -580,7 +644,11 @@ So the `b` is found from the currently stored value. This fact can be exploited.
|
||||
How `Julia` resolves what a variable refers to is described in detail in the manual page [Scope of Variables](https://docs.julialang.org/en/v1/manual/variables-and-scoping/). In this case, the function definition finds variables in the context of where the function was defined, the main workspace, and not where it is called. As seen, this context can be modified after the function definition and prior to the function call. It is only when `b` is needed, that the context is consulted, so the most recent binding is retrieved. Contexts allow the user to repurpose variable names without there being name collision. For example, we typically use `x` as a function argument, and different contexts allow this `x` to refer to different values.
|
||||
|
||||
|
||||
Mostly this works as expected, but at times it can be complicated to reason about. In our example, definitions of the parameters can be forgotten, or the same variable name may have been used for some other purpose. The potential issue is with the parameters, the value for `x` is straightforward, as it is passed into the function. However, we can also pass the parameters, such as $m$ and $b$, as arguments. For parameters, one suggestion is to use [keyword](https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments) arguments. These allow the specification of parameters, but also give a default value. This can make usage explicit, yet still convenient. For example, here is an alternate way of defining a line with parameters `m` and `b`:
|
||||
Mostly this works as expected, but at times it can be complicated to reason about. In our example, definitions of the parameters can be forgotten, or the same variable name may have been used for some other purpose. The potential issue is with the parameters, the value for `x` is straightforward, as it is passed into the function.
|
||||
|
||||
However, we can also pass the parameters, such as $m$ and $b$, as arguments. There are different styles employed.
|
||||
|
||||
For parameters, one suggestion is to use [keyword](https://docs.julialang.org/en/v1/manual/functions/#Keyword-Arguments) arguments. These allow the specification of parameters, but also give a default value. This can make usage explicit, yet still convenient. For example, here is an alternate way of defining a line with parameters `m` and `b`:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -604,7 +672,7 @@ During this call, values for `m` and `b` are found from how the function is call
|
||||
mxplusb(0; m=3, b=2)
|
||||
```
|
||||
|
||||
Keywords are used to mark the parameters whose values are to be changed from the default. Though one can use *positional arguments* for parameters - and there are good reasons to do so - using keyword arguments is a good practice if performance isn't paramount, as their usage is more explicit yet the defaults mean that a minimum amount of typing needs to be done.
|
||||
Keywords are used to mark the parameters whose values are to be changed from the default. Though one can use *positional arguments* for parameters--and there are good reasons to do so--using keyword arguments is a good practice if performance isn't paramount, as their usage is more explicit yet the defaults mean that a minimum amount of typing needs to be done.
|
||||
|
||||
|
||||
Keyword arguments are widely used with plotting commands, as there are numerous options to adjust, but typically only a handful adjusted per call. The `Plots` package whose commands we illustrate throughout these notes starting with the next section has this in its docs: `Plots.jl` follows two simple rules with data and attributes:
|
||||
@@ -640,14 +708,14 @@ For example, here we use a *named tuple* to pass parameters to `f`:
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
function trajectory(x ,p)
|
||||
function trajectory(x, p)
|
||||
g, v0, theta, k = p.g, p.v0, p.theta, p.k # unpack parameters
|
||||
|
||||
a = v0 * cos(theta)
|
||||
(g/(k*a) + tan(theta))* x + (g/k^2) * log(1 - k/a*x)
|
||||
end
|
||||
|
||||
p = (g=9.8, v0=200, theta = 45*pi/180, k=1/2)
|
||||
p = (g=9.8, v0=200, theta=45*pi/180, k=1/2)
|
||||
trajectory(100, p)
|
||||
```
|
||||
|
||||
@@ -687,7 +755,7 @@ The right-hand sides may or may not be familiar, but it should be reasonable to
|
||||
Earlier we saw the `log` function can use a second argument to express the base. This function is basically defined by `log(b,x)=log(x)/log(b)`. The `log(x)` value is the natural log, and this definition just uses the change-of-base formula for logarithms.
|
||||
|
||||
|
||||
But not so fast, on the left side is a function with two arguments and on the right side the functions have one argument - yet they share the same name. How does `Julia` know which to use? `Julia` uses the number, order, and *type* of the positional arguments passed to a function to determine which function definition to use. This is technically known as [multiple dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch) or **polymorphism**. As a feature of the language, it can be used to greatly simplify the number of functions the user must learn. The basic idea is that many functions are "generic" in that they have methods which will work differently in different scenarios.
|
||||
But not so fast, on the left side is a function with two arguments and on the right side the functions have one argument--yet they share the same name. How does `Julia` know which to use? `Julia` uses the number, order, and *type* of the positional arguments passed to a function to determine which function definition to use. This is technically known as [multiple dispatch](http://en.wikipedia.org/wiki/Multiple_dispatch) or **polymorphism**. As a feature of the language, it can be used to greatly simplify the number of functions the user must learn. The basic idea is that many functions are "generic" in that they have methods which will work differently in different scenarios.
|
||||
|
||||
|
||||
:::{.callout-warning}
|
||||
@@ -696,7 +764,7 @@ Multiple dispatch is very common in mathematics. For example, we learn different
|
||||
|
||||
:::
|
||||
|
||||
`Julia` is similarly structured. `Julia` terminology would be to call the operation "`+`" a *generic function* and the different implementations *methods* of "`+`". This allows the user to just need to know a smaller collection of generic concepts yet still have the power of detail-specific implementations. To see how many different methods are defined in the base `Julia` language for the `+` operator, we can use the command `methods(+)`. As there are so many (well over $200$ when `Julia` is started), we illustrate how many different logarithm methods are implemented for "numbers:"
|
||||
`Julia` is similarly structured. `Julia` terminology would be to call the operation "`+`" a *generic function* and the different implementations *methods* of "`+`". This allows the user to just need to know a smaller collection of generic concepts yet still have the power of detail-specific implementations. To see how many different methods are defined in the base `Julia` language for the `+` operator, we can use the command `methods(+)`. As there are so many (well over $100$ when `Julia` is started), we illustrate how many different logarithm methods are implemented for "numbers:"
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -743,7 +811,7 @@ Representing the area of a rectangle in terms of two variables is easy, as the f
|
||||
Area(w, h) = w * h
|
||||
```
|
||||
|
||||
But the other fact about this problem - that the perimeter is $20$ - means that height depends on width. For this question, we can see that $P=2w + 2h$ so that - as a function - `height` depends on `w` as follows:
|
||||
But the other fact about this problem--that the perimeter is $20$--means that height depends on width. For this question, we can see that $P=2w + 2h$ so that--as a function--`height` depends on `w` as follows:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -813,7 +881,7 @@ function shift_right(f; c=0)
|
||||
end
|
||||
```
|
||||
|
||||
That takes some parsing. In the body of the `shift_right` is the definition of a function. But this function has no name– it is *anonymous*. But what it does should be clear - it subtracts $c$ from $x$ and evaluates $f$ at this new value. Since the last expression creates a function, this function is returned by `shift_right`.
|
||||
That takes some parsing. In the body of the `shift_right` is the definition of a function. But this function has no name–-it is *anonymous*. But what it does should be clear--it subtracts $c$ from $x$ and evaluates $f$ at this new value. Since the last expression creates a function, this function is returned by `shift_right`.
|
||||
|
||||
|
||||
So we could have done something more complicated like:
|
||||
@@ -833,7 +901,7 @@ The value of `c` used when `l` is called is the one passed to `shift_right`. Fun
|
||||
|
||||
:::
|
||||
|
||||
Anonymous functions can be created with the `function` keyword, but we will use the "arrow" notation, `arg->body` to create them, The above, could have been defined as:
|
||||
Anonymous functions can be created with the `function` keyword, but we will use the "arrow" notation, `arg->body`, to create them, The above, could have been defined as:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -845,7 +913,11 @@ When the `->` is seen a function is being created.
|
||||
|
||||
:::{.callout-warning}
|
||||
## Warning
|
||||
Generic versus anonymous functions. Julia has two types of functions, generic ones, as defined by `f(x)=x^2` and anonymous ones, as defined by `x -> x^2`. One gotcha is that `Julia` does not like to use the same variable name for the two types. In general, Julia is a dynamic language, meaning variable names can be reused with different types of variables. But generic functions take more care, as when a new method is defined it gets added to a method table. So repurposing the name of a generic function for something else is not allowed. Similarly, repurposing an already defined variable name for a generic function is not allowed. This comes up when we use functions that return functions as we have different styles that can be used: When we defined `l = shift_right(f, c=3)` the value of `l` is assigned an anonymous function. This binding can be reused to define other variables. However, we could have defined the function `l` through `l(x) = shift_right(f, c=3)(x)`, being explicit about what happens to the variable `x`. This would add a method to the generic function `l`. Meaning, we get an error if we tried to assign a variable to `l`, such as an expression like `l=3`. The latter style is inefficient, so is not preferred.
|
||||
Generic versus anonymous functions. Julia has two types of functions, generic ones, as defined by `f(x)=x^2` and anonymous ones, as defined by `x -> x^2`. One gotcha is that `Julia` does not like to use the same variable name for the two types. In general, Julia is a dynamic language, meaning variable names can be reused with different types of variables. But generic functions take more care, as when a new method is defined it gets added to a method table. So repurposing the name of a generic function for something else is not allowed. Similarly, repurposing an already defined variable name for a generic function is not allowed.
|
||||
|
||||
This comes up when we use functions that return functions as we have different styles that can be used: When we defined `l = shift_right(f, c=3)` the value of `l` is assigned to name an anonymous function for later use. This binding can be reused to define other variables.
|
||||
|
||||
However, we could have defined the function `l` through `l(x) = shift_right(f, c=3)(x)`, being explicit about what happens to the variable `x`. This would add a method to the generic function `l`. Meaning, we get an error if we tried to assign a variable to `l`, such as an expression like `l=3`. The latter style is inefficient, so is not preferred.
|
||||
|
||||
:::
|
||||
|
||||
@@ -918,6 +990,10 @@ which picks off the values of `0` and `1` in a somewhat obscure way but less ver
|
||||
|
||||
The `Fix2` function is also helpful when using the `f(x, p)` form for passing parameters to a function. The result of `Base.Fix2(f, p)` is a function with its parameters fixed that can be passed along for plotting or other uses.
|
||||
|
||||
:::{.callout-note}
|
||||
## Fix
|
||||
In Julia v1.12 the `Fix` constructor can fix an arbitrary position of a variadic function.
|
||||
:::
|
||||
|
||||
### The `do` notation
|
||||
|
||||
@@ -1038,9 +1114,7 @@ radioq(choices, answ)
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plt = let
|
||||
gr()
|
||||
empty_style = (xaxis=([], false),
|
||||
yaxis=([], false),
|
||||
empty_style = (xticks=-4:4, yticks=-4:4,
|
||||
framestyle=:origin,
|
||||
legend=false)
|
||||
axis_style = (arrow=true, side=:head, line=(:gray, 1))
|
||||
@@ -1067,12 +1141,19 @@ plt = let
|
||||
S = Shape([(k+1,k) .+ xy for xy in xys])
|
||||
plot!(S; fill=(:white,), line=(:black,1))
|
||||
end
|
||||
|
||||
|
||||
current()
|
||||
end
|
||||
plotly()
|
||||
plt
|
||||
```
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
The `floor` function rounds down. For example, any value in $[k,k+1)$ rounds to $k$ for integer $k$.
|
||||
:::
|
||||
|
||||
@@ -1494,7 +1575,7 @@ Where $N(m)$ counts the number of stars brighter than magnitude $m$ *per* square
|
||||
A [square degree](https://en.wikipedia.org/wiki/Square_degree) is a unit of a solid angle. An entire sphere has a solid angle of $4\pi$ and $4\pi \cdot (180/\pi)^2$ square degrees.
|
||||
|
||||
|
||||
With this we can answer agequestions, such as:
|
||||
With this we can answer questions, such as:
|
||||
|
||||
> How many stars can we see in the sky?
|
||||
|
||||
|
||||
@@ -15,10 +15,17 @@ plotly()
|
||||
---
|
||||
|
||||
|
||||
A (univariate) mathematical function relates or associates values of $x$ to values $y$ using the notation $y=f(x)$. A key point is a given $x$ is associated with just one $y$ value, though a given $y$ value may be associated with several different $x$ values. (Graphically, this is the vertical line test.)
|
||||
A (univariate) mathematical function relates or associates values of $x$ to values $y$ using the notation $y=f(x)$. A key point is a given $x$ is associated with just one $y$ value, though a given $y$ value may be associated with several different $x$ values. (Graphically, this is the horizontal line test.)
|
||||
|
||||
|
||||
We may conceptualize such a relation in many ways: through an algebraic rule; through the graph of $f;$ through a description of what $f$ does; or through a table of paired values, say. For the moment, let's consider a function as a rule that takes in a value of $x$ and outputs a value $y$. If a rule is given defining the function, the computation of $y$ is straightforward. A different question is not so easy: for a given value $y$ what value - or *values* - of $x$ (if any) produce an output of $y$? That is, what $x$ value(s) satisfy $f(x)=y$?
|
||||
We may conceptualize such a relation in many ways:
|
||||
|
||||
* through an algebraic rule;
|
||||
* through the graph of $f$;
|
||||
* through a description of what $f$ does;
|
||||
* or through a table of paired values, say.
|
||||
|
||||
For the moment, let's consider a function as a rule that takes in a value of $x$ and outputs a value $y$. If a rule is given defining the function, the computation of $y$ is straightforward. A different question is not so easy: for a given value $y$ what value--or *values*--of $x$ (if any) produce an output of $y$? That is, what $x$ value(s) satisfy $f(x)=y$?
|
||||
|
||||
|
||||
*If* for each $y$ in some set of values there is just one $x$ value, then this operation associates to each value $y$ a single value $x$, so it too is a function. When that is the case we call this an *inverse* function.
|
||||
@@ -80,7 +87,7 @@ p
|
||||
The graph of a function is a representation of points $(x,f(x))$, so to *find* $y = f(c)$ from the graph, we begin on the $x$ axis at $c$, move vertically to the graph (the point $(c, f(c))$), and then move horizontally to the $y$ axis, intersecting it at $y = f(c)$. The figure shows this for $c=2$, from which we can read that $f(c)$ is about $4$. This is how an $x$ is associated to a single $y$.
|
||||
|
||||
|
||||
If we were to *reverse* the direction, starting at $y = f(d)$ on the $y$ axis and then moving horizontally to the graph, and then vertically to the $x$-axis we end up at a value $d$ with the correct $f(d)$. This allows solving for $x$ knowing $y$ in $y=f(x)$.
|
||||
If we were to *reverse* the direction, starting at $y = f(d)$ on the $y$ axis and then moving horizontally to the graph, and then vertically to the $x$-axis we end up at a value $d$ with the correct value of $f(d)$. This allows solving for $x$ knowing $y$ in $y=f(x)$.
|
||||
|
||||
The operation described will form a function **if** the initial movement horizontally is guaranteed to find *no more than one* value on the graph. That is, to have an inverse function, there can not be two $x$ values corresponding to a given $y$ value. This observation is often visualized through the "horizontal line test" - the graph of a function with an inverse function can only intersect a horizontal line at most in one place.
|
||||
|
||||
@@ -195,7 +202,7 @@ In the section on the [intermediate value theorem](../limits/intermediate_value_
|
||||
## Functions which are not always invertible
|
||||
|
||||
|
||||
Consider the function $f(x) = x^2$. The graph - a parabola - is clearly not *monotonic*. Hence no inverse function exists. Yet, we can solve equations $y=x^2$ quite easily: $y=\sqrt{x}$ *or* $y=-\sqrt{x}$. We know the square root undoes the squaring, but we need to be a little more careful to say the square root is the inverse of the squaring function.
|
||||
Consider the function $f(x) = x^2$. The graph--a parabola--is clearly not *monotonic*. Hence no inverse function exists. Yet, we can solve equations $y=x^2$ quite easily: $y=\sqrt{x}$ *or* $y=-\sqrt{x}$. We know the square root undoes the squaring, but we need to be a little more careful to say the square root is the inverse of the squaring function.
|
||||
|
||||
|
||||
The issue is there are generally *two* possible answers. To avoid this, we might choose to only take the *non-negative* answer. To make this all work as above, we restrict the domain of $f(x)$ and now consider the related function $f(x)=x^2, x \geq 0$. This is now a monotonic function, so will have an inverse function. This is clearly $f^{-1}(x) = \sqrt{x}$. (The $\sqrt{x}$ being defined as the principle square root or the unique *non-negative* answer to $u^2-x=0$.)
|
||||
@@ -231,8 +238,9 @@ Consider again the graph of a monotonic function, in this case $f(x) = x^2 + 2,
|
||||
```{julia}
|
||||
#| hold: true
|
||||
f(x) = x^2 + 2
|
||||
plot(f, 0, 4, legend=false)
|
||||
plot!([2,2,0], [0,f(2),f(2)])
|
||||
plot(f, 0, 4; yticks=[2,4,8,16],
|
||||
legend=false, framestyle=:origin)
|
||||
plot!([(2,0), (2, f(2)), (0, f(2))])
|
||||
```
|
||||
|
||||
The graph is shown over the interval $(0,4)$, but the *domain* of $f(x)$ is all $x \geq 0$. The *range* of $f(x)$ is clearly $2 \leq y \leq \infty$.
|
||||
@@ -241,24 +249,18 @@ The graph is shown over the interval $(0,4)$, but the *domain* of $f(x)$ is all
|
||||
The lines layered on the plot show how to associate an $x$ value to a $y$ value or vice versa (as $f(x)$ is one-to-one). The domain then of the inverse function is all the $y$ values for which a corresponding $x$ value exists: this is clearly all values bigger or equal to $2$. The *range* of the inverse function can be seen to be all the images for the values of $y$, which would be all $x \geq 0$. This gives the relationship:
|
||||
|
||||
|
||||
> the *range* of $f(x)$ is the *domain* of $f^{-1}(x)$; furthermore the *domain* of $f(x)$ is the *range* for $f^{-1}(x)$;
|
||||
|
||||
|
||||
> * the *domain* of $f^{-1}(x)$ is the *range* of $f(x)$;
|
||||
> * the *range* of $f^{-1}(x)$ is the *domain* of $f(x)$;
|
||||
|
||||
From this we can see if we start at $x$, apply $f$ we get $y$, if we then apply $f^{-1}$ we will get back to $x$ so we have:
|
||||
|
||||
|
||||
> For all $x$ in the domain of $f$: $f^{-1}(f(x)) = x$.
|
||||
|
||||
|
||||
|
||||
Similarly, were we to start on the $y$ axis, we would see:
|
||||
|
||||
|
||||
> For all $x$ in the domain of $f^{-1}$: $f(f^{-1}(x)) = x$.
|
||||
|
||||
|
||||
|
||||
In short $f^{-1} \circ f$ and $f \circ f^{-1}$ are both identity functions, though on possibly different domains.
|
||||
|
||||
|
||||
@@ -280,11 +282,12 @@ Let's see this in action. Take the function $2^x$. We can plot it by generating
|
||||
f(x) = 2^x
|
||||
xs = range(0, 2, length=50)
|
||||
ys = f.(xs)
|
||||
plot(xs, ys, color=:blue, label="f")
|
||||
plot!(ys, xs, color=:red, label="f⁻¹") # the inverse
|
||||
plot(xs, ys; color=:blue, label="f",
|
||||
aspect_ratio=:equal, framestyle=:origin, xlims=(0,4))
|
||||
plot!(ys, xs; color=:red, label="f⁻¹") # the inverse
|
||||
```
|
||||
|
||||
By flipping around the $x$ and $y$ values in the `plot!` command, we produce the graph of the inverse function - when viewed as a function of $x$. We can see that the domain of the inverse function (in red) is clearly different from that of the function (in blue).
|
||||
By flipping around the $x$ and $y$ values in the `plot!` command, we produce the graph of the inverse function--when viewed as a function of $x$. We can see that the domain of the inverse function (in red) is clearly different from that of the function (in blue).
|
||||
|
||||
|
||||
The inverse function graph can be viewed as a symmetry of the graph of the function. Flipping the graph for $f(x)$ around the line $y=x$ will produce the graph of the inverse function: Here we see for the graph of $f(x) = x^{1/3}$ and its inverse function:
|
||||
@@ -295,15 +298,16 @@ The inverse function graph can be viewed as a symmetry of the graph of the funct
|
||||
f(x) = cbrt(x)
|
||||
xs = range(-2, 2, length=150)
|
||||
ys = f.(xs)
|
||||
plot(xs, ys, color=:blue, aspect_ratio=:equal, legend=false)
|
||||
plot!(ys, xs, color=:red)
|
||||
plot!(identity, color=:green, linestyle=:dash)
|
||||
x, y = 1/2, f(1/2)
|
||||
plot!([x,y], [y,x], color=:green, linestyle=:dot)
|
||||
plot(xs, ys; color=:blue,
|
||||
aspect_ratio=:equal, legend=false)
|
||||
plot!(ys, xs; line=(:red,))
|
||||
plot!(identity; line=(:green, :dash))
|
||||
x = 1/4
|
||||
y = f(x)
|
||||
plot!([(x,y), (y,x)]; line=(:green, :dot))
|
||||
```
|
||||
|
||||
We drew a line connecting $(1/2, f(1/2))$ to $(f(1/2),1/2)$. We can see that it crosses the line $y=x$ perpendicularly, indicating that points are symmetric about this line. (The plotting argument `aspect_ratio=:equal` ensures that the $x$ and $y$ axes are on the same scale, so that this type of line will look perpendicular.)
|
||||
|
||||
We drew a line connecting $(1/4, f(1/4))$ to $(f(1/4),1/4)$. We can see that it crosses the line $y=x$ perpendicularly, indicating that points are symmetric about this line. (The plotting argument `aspect_ratio=:equal` ensures that the $x$ and $y$ axes are on the same scale, so that this type of line will look perpendicular.)
|
||||
|
||||
One consequence of this symmetry, is that if $f$ is strictly increasing, then so is its inverse.
|
||||
|
||||
@@ -472,7 +476,7 @@ plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
The key here is that the shape of $f(x)$ near $x=c$ is somewhat related to the shape of $f^{-1}(x)$ at $f(c)$. In this case, if we use the tangent line as a fill in for how steep a function is, we see from the relationship that if $f(x)$ is "steep" at $x=c$, then $f^{-1}(x)$ will be "shallow" at $x=f(c)$.
|
||||
The key here is that the shape of $f(x)$ near $x=c$ is directly related to the shape of $f^{-1}(x)$ at $f(c)$. In this case, if we use the tangent line as a fill in for how steep a function is, we see from the relationship that if $f(x)$ is "steep" at $x=c$, then $f^{-1}(x)$ will be "shallow" at $x=f(c)$.
|
||||
|
||||
|
||||
## Questions
|
||||
|
||||
@@ -165,7 +165,7 @@ Integers are often used casually, as they come about from parsing. As with a cal
|
||||
|
||||
As per IEEE Standard 754, the `Float64` type gives 52 bits to the precision (with an additional implied one), 11 bits to the exponent and the other bit is used to represent the sign. Positive, finite, floating point numbers have a range approximately between $10^{-308}$ and $10^{308}$, as 308 is about $\log_{10} 2^{1023}$. The numbers are not evenly spread out over this range, but, rather, are much more concentrated closer to $0$.
|
||||
|
||||
The use of 32-bit floating point values is common, as some widley used computer chips expect this. These values have a narrower range of possible values.
|
||||
The use of 32-bit floating point values is common, as some widely used computer chips expect this. These values have a narrower range of possible values.
|
||||
|
||||
:::{.callout-warning}
|
||||
## More on floating point numbers
|
||||
@@ -404,6 +404,42 @@ Though complex numbers are stored as pairs of numbers, the imaginary unit, `im`,
|
||||
|
||||
:::
|
||||
|
||||
### Strings and symbols
|
||||
|
||||
For text, `Julia` has a `String` type. When double quotes are used to specify a string, the parser creates this type:
|
||||
|
||||
```{julia}
|
||||
x = "The quick brown fox jumped over the lazy dog"
|
||||
typeof(x)
|
||||
```
|
||||
|
||||
Values can be inserted into a string through *interpolation* using a dollar sign.
|
||||
|
||||
```{julia}
|
||||
animal = "lion"
|
||||
x = "The quick brown $(animal) jumped over the lazy dog"
|
||||
```
|
||||
|
||||
The use of parentheses allows more complicated expressions; it isn't always necessary.
|
||||
|
||||
Longer strings can be produced using *triple* quotes:
|
||||
|
||||
```{julia}
|
||||
lincoln = """
|
||||
Four score and seven years ago our fathers brought forth, upon this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.
|
||||
"""
|
||||
```
|
||||
|
||||
Strings are comprised of *characters* which can be produced directly using *single* quotes:
|
||||
|
||||
```{julia}
|
||||
'c'
|
||||
```
|
||||
|
||||
We won't use these.
|
||||
|
||||
Finally, `Julia` has *symbols* which are *interned* strings which are used as identifiers. Symbols are used for advanced programming techniques; we will only see them as shortcuts to specify plotting arguments.
|
||||
|
||||
## Type stability
|
||||
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ This section will use the following packages:
|
||||
```{julia}
|
||||
using CalculusWithJulia
|
||||
using Plots
|
||||
plotly()
|
||||
plotly();
|
||||
```
|
||||
|
||||
```{julia}
|
||||
@@ -18,6 +18,7 @@ plotly()
|
||||
using Roots
|
||||
using SymPy
|
||||
using DataFrames
|
||||
using Latexify
|
||||
|
||||
nothing
|
||||
```
|
||||
@@ -83,7 +84,7 @@ plotly()
|
||||
|
||||
(Certain graphics are produced with the `gr()` backend.)
|
||||
|
||||
With `Plots` loaded, it is straightforward to graph a function.
|
||||
With `Plots` loaded and a backend chosen, it is straightforward to graph a function.
|
||||
|
||||
|
||||
For example, to graph $f(x) = 1 - x^2/2$ over the interval $[-3,3]$ we have:
|
||||
@@ -97,8 +98,9 @@ plot(f, -3, 3)
|
||||
The `plot` command does the hard work behind the scenes. It needs $2$ pieces of information declared:
|
||||
|
||||
|
||||
* **What** to plot. With this invocation, this detail is expressed by passing a function object to `plot`
|
||||
* **Where** to plot; the `xmin` and `xmax` values. As with a sketch, it is impossible in this case to render a graph with all possible $x$ values in the domain of $f$, so we need to pick some viewing window. In the example this is $[-3,3]$ which is expressed by passing the two endpoints as the second and third arguments.
|
||||
* **What** to plot. With this invocation, this detail is expressed by passing a function object to `plot`
|
||||
|
||||
* **Where** to plot; the `xmin` and `xmax` values. As with a sketch, it is impossible in this case to render a graph with all possible $x$ values in the domain of $f$, so we need to pick some viewing window. In the example this has $x$ limits of $[-3,3]$; expressed by passing the two endpoints as the second and third arguments.
|
||||
|
||||
|
||||
Plotting a function is then this simple: `plot(f, xmin, xmax)`.
|
||||
@@ -198,9 +200,9 @@ This choices does *not* show the $x-y$ axes. As such, we might layer on the axes
|
||||
To emphasize concepts, we may stylize a function graph, rather than display the basic graphic. For example, in this graphic highlighting the amount the function goes up as it moves from $1$ to $x$:
|
||||
|
||||
```{julia}
|
||||
gr()
|
||||
#| echo: false
|
||||
let
|
||||
plt = let
|
||||
gr()
|
||||
f(x) = x^2
|
||||
|
||||
empty_style = (xaxis=([], false),
|
||||
@@ -239,6 +241,7 @@ let
|
||||
])
|
||||
current()
|
||||
end
|
||||
plt
|
||||
```
|
||||
|
||||
```{julia}
|
||||
@@ -315,6 +318,7 @@ plot(xs, ys)
|
||||
This plots the points as pairs and then connects them in order using straight lines. Basically, it creates a dot-to-dot graph. The above graph looks primitive, as it doesn't utilize enough points.
|
||||
|
||||
|
||||
|
||||
##### Example: Reflections
|
||||
|
||||
|
||||
@@ -396,17 +400,16 @@ The graph is that of the "inverse function" for $\sin(x), x \text{ in } [-\pi/2,
|
||||
When plotting a univariate function there are three basic patterns that can be employed. We have examples above of:
|
||||
|
||||
|
||||
* `plot(f, xmin, xmax)` uses an adaptive algorithm to identify values for $x$ in the interval `[xmin, xmas]`,
|
||||
* `plot(xs, f.(xs))` to manually choose the values of $x$ to plot points for, and
|
||||
* `plot(f, xmin, xmax)` uses a recipe implementing an adaptive algorithm to identify values for $x$ in the interval `[xmin, xmas]`,
|
||||
|
||||
* `plot(xs, f.(xs))` to manually choose the values of $x$ to plot points for, and
|
||||
|
||||
Finally, there is a merging of the first two following the pattern:
|
||||
|
||||
* `plot(xs, f)`
|
||||
|
||||
|
||||
Finally there is a merging of these following either of these patterns:
|
||||
|
||||
|
||||
* `plot(f, xs)` *or* `plot(xs, f)`
|
||||
|
||||
|
||||
Both require a manual choice of the values of the $x$-values to plot, but the broadcasting is carried out in the `plot` command. This style is convenient, for example, to down sample the $x$ range to see the plotting mechanics, such as:
|
||||
All require a manual choice of the values of the $x$-values to plot, but the broadcasting is carried out in the `plot` command. This style is convenient, for example, to down sample the $x$ range to see the plotting mechanics, such as:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -416,10 +419,10 @@ plot(0:pi/4:2pi, sin)
|
||||
#### NaN values
|
||||
|
||||
|
||||
At times it is not desirable to draw lines between each successive point. For example, if there is a discontinuity in the function or if there were a vertical asymptote, such as what happens at $0$ with $f(x) = 1/x$.
|
||||
At times it is not desirable to draw lines between each successive point. For example, if there is a discontinuity in the function or if there were a vertical asymptote.
|
||||
|
||||
|
||||
The most straightforward plot is dominated by the vertical asymptote at $x=0$:
|
||||
For example,what happens at $0$ with $f(x) = 1/x$. The most straightforward plot is dominated by the vertical asymptote at $x=0$:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -437,10 +440,10 @@ As we see, even with this adjustment, the spurious line connecting the points wi
|
||||
plot(q, -1, 1, ylims=(-10,10))
|
||||
```
|
||||
|
||||
The dot-to-dot algorithm, at some level, assumes the underlying function is continuous; here $q(x)=1/x$ is not.
|
||||
The dot-to-dot algorithm, at some level, assumes the underlying function is *continuous*; here $q(x)=1/x$ is not.
|
||||
|
||||
|
||||
There is a convention for most plotting programs that **if** the $y$ value for a point is `NaN` that no lines will connect to that point, `(x,NaN)`. `NaN` conveniently appears in many cases where a plot may have an issue, though not with $1/x$ as `1/0` is `Inf` and not `NaN`. (Unlike, say, `0/0` which is NaN.)
|
||||
There is a convention for most plotting programs that **if** the $y$ value for a point is `NaN` then no lines will connect to that point, `(x,NaN)`. `NaN` conveniently appears in many cases where a plot may have an issue, though not with $1/x$ as `1/0` is `Inf` and not `NaN`. (Unlike, say, `0/0` which is NaN.)
|
||||
|
||||
|
||||
Here is one way to plot $q(x) = 1/x$ over $[-1,1]$ taking advantage of this convention:
|
||||
@@ -457,7 +460,7 @@ plot(xs, ys)
|
||||
By using an odd number of points, we should have that $0.0$ is amongst the `xs`. The next to last line replaces the $y$ value that would be infinite with `NaN`.
|
||||
|
||||
|
||||
As a recommended alternative, we might modify the function so that if it is too large, the values are replaced by `NaN`. Here is one such function consuming a function and returning a modified function put to use to make this graph:
|
||||
The above is fussy. As a recommended alternative, we might modify the function so that if it is too large, the values are replaced by `NaN`. Here is one such function consuming a function and returning a modified function put to use to make this graph:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -471,7 +474,7 @@ plot(rangeclamp(x -> 1/x), -1, 1)
|
||||
## Layers
|
||||
|
||||
|
||||
Graphing more than one function over the same viewing window is often desirable. Though this is easily done in `Plots` by specifying a vector of functions as the first argument to `plot` instead of a single function object, we instead focus on building the graph layer by layer.
|
||||
Graphing more than one function over the same viewing window is often desirable. Though this is easily done all at once in `Plots` by specifying a vector of functions as the first argument to `plot` instead of a single function object, we instead focus on building the graph layer by layer.^[The style of `Plots` is to combine multiple *series* to plot into one object and let `Plots` sort out which (every column is treated as a separate series). This can be very efficient from a programming perspective, but we leave it for power users. The use of layers, seems much easier to understand.]
|
||||
|
||||
|
||||
For example, to see that a polynomial and the cosine function are "close" near $0$, we can plot *both* $\cos(x)$ and the function $f(x) = 1 - x^2/2$ over $[-\pi/2,\pi/2]$:
|
||||
@@ -505,8 +508,8 @@ For another example, suppose we wish to plot the function $f(x)=x\cdot(x-1)$ ove
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
f(x) = x*(x-1)
|
||||
plot(f, -1, 2, legend=false) # turn off legend
|
||||
f(x) = x * (x-1)
|
||||
plot(f, -1, 2; legend=false) # turn off legend
|
||||
plot!(zero)
|
||||
scatter!([0,1], [0,0])
|
||||
```
|
||||
@@ -514,43 +517,53 @@ scatter!([0,1], [0,0])
|
||||
The $3$ main functions used in these notes for adding layers are:
|
||||
|
||||
|
||||
* `plot!(f, a, b)` to add the graph of the function `f`; also `plot!(xs, ys)`
|
||||
* `scatter!(xs, ys)` to add points $(x_1, y_1), (x_2, y_2), \dots$.
|
||||
* `annotate!((x,y, label))` to add a label at $(x,y)$
|
||||
* `plot!(f, a, b)` to add the graph of the function `f`; also `plot!(xs, ys)`
|
||||
|
||||
* `scatter!(xs, ys)` to add points $(x_1, y_1), (x_2, y_2), \dots$.
|
||||
|
||||
* `annotate!((x,y, label))` to add a label at $(x,y)$
|
||||
|
||||
|
||||
:::{.callout-warning}
|
||||
## Warning
|
||||
## Trailing ! convention
|
||||
Julia has a convention to use functions named with a `!` suffix to indicate that they mutate some object. In this case, the object is the current graph, though it is implicit. Both `plot!`, `scatter!`, and `annotate!` (others too) do this by adding a layer.
|
||||
|
||||
:::
|
||||
|
||||
## Additional arguments
|
||||
|
||||
|
||||
The `Plots` package provides many arguments for adjusting a graphic, here we mention just a few of the [attributes](https://docs.juliaplots.org/latest/attributes/):
|
||||
The `Plots` package uses positional arguments for input data and keyword arguments for [attributes](https://docs.juliaplots.org/latest/attributes/).
|
||||
The `Plots` package provides many such arguments for adjusting a graphic, here we mention just a few:
|
||||
|
||||
|
||||
* `plot(..., title="main title", xlab="x axis label", ylab="y axis label")`: add title and label information to a graphic
|
||||
* `plot(..., color="green")`: this argument can be used to adjust the color of the drawn figure (color can be a string,`"green"`, or a symbol, `:green`, among other specifications)
|
||||
* `plot(..., linewidth=5)`: this argument can be used to adjust the width of drawn lines
|
||||
* `plot(..., xlims=(a,b), ylims=(c,d))`: either or both `xlims` and `ylims` can be used to control the viewing window
|
||||
* `plot(..., linestyle=:dash)`: will change the line style of the plotted lines to dashed lines. Also `:dot`, ...
|
||||
* `plot(..., aspect_ratio=:equal)`: will keep $x$ and $y$ axis on same scale so that squares look square.
|
||||
* `plot(..., legend=false)`: by default, different layers will be indicated with a legend, this will turn off this feature
|
||||
* `plot(..., label="a label")` the `label` attribute will show up when a legend is present. Using an empty string, `""`, will suppress add the layer to the legend.
|
||||
* `plot(...; title="main title", xlab="x axis label", ylab="y axis label")`: add title and label information to a graphic
|
||||
* `plot(...; color="green")`: this argument can be used to adjust the color of the drawn figure (color can be a string,`"green"`, or a symbol, `:green`, among other specifications)
|
||||
* `plot(...; linewidth=5)`: this argument can be used to adjust the width of drawn lines
|
||||
* `plot(...; linestyle=:dash)`: will change the line style of the plotted lines to dashed lines. Also `:dot`, ...
|
||||
* `plot(...; label="a label")` the `label` attribute will show up when a legend is present. Using an empty string, `""`, will suppress add the layer to the legend.
|
||||
* `plot(...; legend=false)`: by default, different layers will be indicated with a legend, this will turn off this feature
|
||||
* `plot(...; xlims=(a,b), ylims=(c,d))`: either or both `xlims` and `ylims` can be used to control the viewing window
|
||||
* `plot(...; xticks=[xs..], yticks=[ys...]: either or both `xticks` and `yticks` can be used to specify where the tick marks are to be drawn
|
||||
* `plot(...; aspect_ratio=:equal)`: will keep $x$ and $y$ axis on same scale so that squares look square.
|
||||
* `plot(...; framestyle=:origin)`: The default `framestyle` places $x$-$y$ guides on the edges; this specification places them on the $x-y$ plane.
|
||||
|
||||
|
||||
For plotting points with `scatter`, or `scatter!` the markers can be adjusted via
|
||||
|
||||
|
||||
* `scatter(..., markersize=5)`: increase marker size
|
||||
* `scatter(..., marker=:square)`: change the marker (uses a symbol, not a string to specify)
|
||||
* `scatter(...; markersize=5)`: increase marker size
|
||||
* `scatter(...; marker=:square)`: change the marker (uses a symbol, not a string to specify)
|
||||
|
||||
|
||||
Of course, zero, one, or more of these can be used on any given call to `plot`, `plot!`, `scatter`, or `scatter!`.
|
||||
|
||||
There are also several *shorthands* in `Plots` that allows several related attributes to be specified to a single argument that is disambiguated using the type of the value. (Eg. `line=(5, 0.25, "blue")` will specify the line have width `5`, color `blue`, and alpha-transparency `0.25`.)
|
||||
### Shorthands
|
||||
|
||||
There are also several *shorthands* in `Plots` that allows several related attributes to be specified to a single argument that is disambiguated using the type of the value. A few used herein are:
|
||||
|
||||
* `line`. For example, `line=(5, 0.25, "blue")` will specify `linewidth=5` (integer), `linecolor="blue"` (string or symbol), `linealpha=0.25` (floating point)
|
||||
* `marker`. For example `marker=(:star, 5)` will specify `markerstyle=:star` (symbol) and `markersize=5` (integer).
|
||||
* `fill`. For example `fill=(:blue, 0.25)` will specify `fillcolor=:blue` (string or symbol) and `fillalpha=0.25` (floating point).
|
||||
|
||||
#### Example: Bresenham's algorithm
|
||||
|
||||
@@ -607,9 +620,9 @@ p = plot(f, x₀, x₁; legend=false, aspect_ratio=:equal,
|
||||
col = RGBA(.64,.64,.64, 0.25)
|
||||
for xy ∈ xs
|
||||
x, y = xy
|
||||
scatter!([x], [y]; markersize=5)
|
||||
scatter!([x+1], [y - 1/2], markersize=5, markershape=:star7)
|
||||
plot!(Shape(x .+ [0, 1, 1, 0], y .+ [0, 0, -1, -1]), color=col)
|
||||
scatter!([x], [y]; marker=(5,))
|
||||
scatter!([x+1], [y - 1/2]; marker=(5,:star))
|
||||
plot!(Shape(x .+ [0, 1, 1, 0], y .+ [0, 0, -1, -1]); color=col)
|
||||
end
|
||||
p
|
||||
```
|
||||
@@ -618,14 +631,46 @@ We see a number of additional arguments used: different marker sizes and shapes
|
||||
|
||||
Of course, generalizations for positive slope and slope with magnitude greater than $1$ are needed. As well, this basic algorithm could be optimized, especially if it is part of a lower-level drawing primitive. But this illustrates the considerations involved.
|
||||
|
||||
## Points, lines, polygons
|
||||
|
||||
Two basic objects to graph are points and lines. Add to these polygons.
|
||||
|
||||
A point in two-dimensional space has two coordinates, often denoted by $(x,y)$. In `Julia`, the same notation produces a `tuple`. Using square brackets, as in `[x,y]`, produces a vector. Vectors are are more commonly used in these notes, as we have seen there are algebraic operations defined for them. However, tuples have other advantages and are how `Plots` designates a point.
|
||||
|
||||
The plot command `plot(xs, ys)` plots the points $(x_1,y_1), \dots, (x_n, y_n)$ and then connects adjacent points with with lines. The command `scatter(xs, ys)` just plots the points.
|
||||
|
||||
However, the points might be more naturally specified as coordinate pairs. If tuples are used to pair them off, then `Plots` will plot a vector of tuples as a sequence of points through `plot([(x1,y1), (x2, y2), ..., (xn, yn)])`:
|
||||
|
||||
```{julia}
|
||||
pts = [( 1, 0), ( 1/4, 1/4), (0, 1), (-1/4, 1/4),
|
||||
(-1, 0), (-1/4, -1/4), (0, -1), ( 1/4, -1/4)]
|
||||
scatter(pts; legend=false)
|
||||
```
|
||||
|
||||
A line segment simply connects two points. While these can be specified as vectors of $x$ and $y$ values, again it may be more convenient to use coordinate pairs to specify the points. Continuing the above, we can connect adjacent points with line segments:
|
||||
|
||||
```{julia}
|
||||
plot!(pts; line=(:gray, 0.5, :dash))
|
||||
```
|
||||
|
||||
This uses the shorthand notation of `Plots` to specify `linecolor=:gray, linealpha=0.5, linestyle=:dash`. To plot just a line segment, just specifying two points suffices.
|
||||
|
||||
The four-pointed star is not closed off, as there isn't a value from the last point to the first point. A polygon closes itself off. The `Shape` function can take a vector of points or a pair of `xs` and `ys` to specify a polygon. When these are plotted, the arguments to `fill` describe the interior of the polygon, the arguments to `line` the boundary:
|
||||
|
||||
|
||||
```{julia}
|
||||
plot(Shape(pts); fill=(:gray, 0.25), line=(:black, 2), legend=false)
|
||||
scatter!(pts)
|
||||
```
|
||||
|
||||
|
||||
## Graphs of parametric equations
|
||||
|
||||
|
||||
If we have two functions $f(x)$ and $g(x)$ there are a few ways to investigate their joint behavior. As just mentioned, we can graph both $f$ and $g$ over the same interval using layers. Such a graph allows an easy comparison of the shape of the two functions and can be useful in solving $f(x) = g(x)$. For the latter, the graph of $h(x) = f(x) - g(x)$ is also of value: solutions to $f(x)=g(x)$ appear as crossing points on the graphs of `f` and `g`, whereas they appear as zeros (crossings of the $x$-axis) when `h` is plotted.
|
||||
If we have two functions $f(x)$ and $g(x)$ there are a few ways to investigate their joint behavior. As mentioned, we can graph both $f$ and $g$ over the same interval using layers. Such a graph allows an easy comparison of the shape of the two functions and can be useful in solving $f(x) = g(x)$, as the $x$ solutions are where the two curves intersect.
|
||||
|
||||
|
||||
A different graph can be made to compare the two functions side-by-side. This is a parametric plot. Rather than plotting points $(x,f(x))$ and $(x,g(x))$ with two separate graphs, the graph consists of points $(f(x), g(x))$. We illustrate with some examples below:
|
||||
A different graph can be made to compare the two functions side-by-side. This is a parametric plot. Rather than plotting points $(x,f(x))$ and $(x,g(x))$ with two separate graphs, the graph consists of points $(f(x), g(x))$ over a range of $x$ values. We illustrate with some examples below:
|
||||
|
||||
|
||||
##### Example
|
||||
@@ -643,7 +688,7 @@ plot(f.(ts), g.(ts), aspect_ratio=:equal) # make equal axes
|
||||
Any point $(a,b)$ on this graph is represented by $(\cos(t), \sin(t))$ for some value of $t$, and in fact multiple values of $t$, since $t + 2k\pi$ will produce the same $(a,b)$ value as $t$ will.
|
||||
|
||||
|
||||
Making the parametric plot is similar to creating a plot using lower level commands. There a sequence of values is generated to approximate the $x$ values in the graph (`xs`), a set of commands to create the corresponding function values (e.g., `f.(xs)`), and some instruction on how to represent the values, in this case with lines connecting the points (the default for `plot` for two sets of numbers).
|
||||
Making the parametric plot is similar to creating a plot using lower level commands. There a sequence of values is generated to approximate the $x$ values in the graph (`xs`), a set of commands to create the corresponding function values (e.g., `f.(xs)`), and some instruction on how to represent the values, in this case with lines connecting the points (the default for `plot` for two vectors of numbers).
|
||||
|
||||
|
||||
In this next plot, the angle values are chosen to be the familiar ones, so the mechanics of the graph can be emphasized. Only the upper half is plotted:
|
||||
@@ -653,7 +698,7 @@ In this next plot, the angle values are chosen to be the familiar ones, so the m
|
||||
#| hold: true
|
||||
#| echo: false
|
||||
θs =[0, PI/6, PI/4, PI/3, PI/2, 2PI/3, 3PI/4,5PI/6, PI]
|
||||
DataFrame(θ=θs, x=cos.(θs), y=sin.(θs))
|
||||
latexify(DataFrame(θ=θs, x=cos.(θs), y=sin.(θs)))
|
||||
```
|
||||
|
||||
```{julia}
|
||||
@@ -718,7 +763,7 @@ This graph is *nearly* a straight line. At the point $(0,0)=(f(0), g(0))$, we se
|
||||
##### Example: Etch A Sketch
|
||||
|
||||
|
||||
[Etch A sketch](http://en.wikipedia.org/wiki/Etch_A_Sketch) is a drawing toy where two knobs control the motion of a pointer, one knob controlling the $x$ motion, the other the $y$ motion. The trace of the movement of the pointer is recorded until the display is cleared by shaking. Shake to clear is now a motion incorporated by some smart-phone apps.
|
||||
[Etch A Sketch](http://en.wikipedia.org/wiki/Etch_A_Sketch) is a drawing toy where two knobs control the motion of a pointer, one knob controlling the $x$ motion, the other the $y$ motion. The trace of the movement of the pointer is recorded until the display is cleared by shaking. Shake to clear is now a motion incorporated by some smart-phone apps.
|
||||
|
||||
|
||||
Playing with the toy makes a few things become clear:
|
||||
@@ -757,38 +802,6 @@ plot(f, g, 0, max((R-r)/r, r/(R-r))*2pi)
|
||||
In the above, one can fix $R=1$. Then different values for `r` and `rho` will produce different graphs. These graphs will be periodic if $(R-r)/r$ is a rational. (Nothing about these equations requires $\rho < r$.)
|
||||
|
||||
|
||||
## Points, lines, polygons
|
||||
|
||||
Two basic objects to graph are points and lines.
|
||||
|
||||
A point in two-dimensional space has two coordinates, often denoted by $(x,y)$. In `Julia`, the same notation produces a `tuple`. Using square brackets, as in `[x,y]`, produces a vector. Vectors are usually used, as we have seen there are algebraic operations defined for them. However, tuples have other advantages and are how `Plots` designates a point.
|
||||
|
||||
The plot command `plot(xs, ys)` plots the points $(x_1,y_1), \dots, (x_n, y_n)$ and then connects adjacent points with with lines. The command `scatter(xs, ys)` just plots the points.
|
||||
|
||||
However, the points might be more naturally specified as coordinate pairs. If tuples are used to pair them off, then `Plots` will plot a vector of tuples as a sequence of points:
|
||||
|
||||
```{julia}
|
||||
pts = [(1, 0), (1/4, 1/4), (0, 1), (-1/4, 1/4), (-1, 0),
|
||||
(-1/4, -1/4), (0, -1), (1/4, -1/4)]
|
||||
scatter(pts; legend=false)
|
||||
```
|
||||
|
||||
A line segment simply connects two points. While these can be specified as vectors of $x$ and $y$ values, again it may be more convenient to use coordinate pairs to specify the points. Continuing the above, we can connect adjacent points with line segments:
|
||||
|
||||
```{julia}
|
||||
plot!(pts; line=(:gray, 0.5, :dash))
|
||||
```
|
||||
|
||||
This uses the shorthand notation of `Plots` to specify `linecolor=:gray, linealpha=0.5, linestyle=:dash`. To plot just a line segment, just specifying two points suffices.
|
||||
|
||||
The four-pointed star is not closed off, as there isn't a value from the last point to the first point. A polygon closes itself off. The `Shape` function can take a vector of points or a pair of `xs` and `ys` to specify a polygon. When these are plotted, the arguments to `fill` describe the interior of the polygon, the arguments to `line` the boundary:
|
||||
|
||||
|
||||
```{julia}
|
||||
plot(Shape(pts); fill=(:gray, 0.25), line=(:black, 2), legend=false)
|
||||
scatter!(pts)
|
||||
```
|
||||
|
||||
|
||||
|
||||
## Questions
|
||||
|
||||
@@ -51,7 +51,12 @@ $$
|
||||
gr()
|
||||
anim = @animate for m in 2:2:10
|
||||
fn = x -> x^m
|
||||
plot(fn, -1, 1, size = fig_size, legend=false, title="graph of x^{$m}", xlims=(-1,1), ylims=(-.1,1))
|
||||
title = L"graph of $x^{%$m}$"
|
||||
plot(fn, -1, 1;
|
||||
size = fig_size,
|
||||
legend=false,
|
||||
title=title,
|
||||
xlims=(-1,1), ylims=(-.1,1))
|
||||
end
|
||||
|
||||
imgfile = tempname() * ".gif"
|
||||
@@ -96,7 +101,12 @@ $$
|
||||
gr()
|
||||
anim = @animate for m in [-5, -2, -1, 1, 2, 5, 10, 20]
|
||||
fn = x -> m * x
|
||||
plot(fn, -1, 1, size = fig_size, legend=false, title="m = $m", xlims=(-1,1), ylims=(-20, 20))
|
||||
title = L"m = %$m"
|
||||
plot(fn, -1, 1;
|
||||
size = fig_size,
|
||||
legend=false,
|
||||
title=title,
|
||||
xlims=(-1,1), ylims=(-20, 20))
|
||||
end
|
||||
|
||||
imgfile = tempname() * ".gif"
|
||||
@@ -301,7 +311,9 @@ float(y)
|
||||
|
||||
|
||||
|
||||
The use of the generic `float` method returns a floating point number. `SymPy` objects have their own internal types. To preserve these on conversion to a related `Julia` value, the `N` function from `SymPy` is useful:
|
||||
The use of the generic `float` method returns a floating point number. (The `.evalf()` method of `SymPy` objects uses `SymPy` to produce floating point versions of symbolic values.
|
||||
|
||||
`SymPy` objects have their own internal types. To preserve these on conversion to a related `Julia` value, the `N` function from `SymPy` is useful:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -310,14 +322,7 @@ p = -16x^2 + 100
|
||||
N(p(2))
|
||||
```
|
||||
|
||||
Where `convert(T, x)` requires a specification of the type to convert `x` to, `N` attempts to match the data type used by SymPy to store the number. As such, the output type of `N` may vary (rational, a BigFloat, a float, etc.) For getting more digits of accuracy, a precision can be passed to `N`. The following command will take the symbolic value for $\pi$, `PI`, and produce about $60$ digits worth as a `BigFloat` value:
|
||||
|
||||
|
||||
```{julia}
|
||||
N(PI, 60)
|
||||
```
|
||||
|
||||
Conversion by `N` will fail if the value to be converted contains free symbols, as would be expected.
|
||||
Where `convert(T, x)` requires a specification of the type to convert `x` to, `N` attempts to match the data type used by SymPy to store the number. As such, the output type of `N` may vary (rational, a BigFloat, a float, etc.) Conversion by `N` will fail if the value to be converted contains free symbols, as would be expected.
|
||||
|
||||
|
||||
### Converting symbolic expressions into Julia functions
|
||||
@@ -362,6 +367,8 @@ pp = lambdify(p, (x,a,b))
|
||||
pp(1,2,3) # computes 2*1^2 + 3
|
||||
```
|
||||
|
||||
(We suggest using the pair notation when there is more than one variable.)
|
||||
|
||||
## Graphical properties of polynomials
|
||||
|
||||
|
||||
@@ -394,7 +401,12 @@ To investigate this last point, let's consider the case of the monomial $x^n$. W
|
||||
gr()
|
||||
anim = @animate for m in 0:2:12
|
||||
fn = x -> x^m
|
||||
plot(fn, -1.2, 1.2, size = fig_size, legend=false, xlims=(-1.2, 1.2), ylims=(0, 1.2^12), title="x^{$m} over [-1.2, 1.2]")
|
||||
title = L"$x^{%$m}$ over $[-1.2, 1.2]$"
|
||||
plot(fn, -1.2, 1.2;
|
||||
size = fig_size,
|
||||
legend=false,
|
||||
xlims=(-1.2, 1.2), ylims=(0, 1.2^12),
|
||||
title=title)
|
||||
end
|
||||
|
||||
imgfile = tempname() * ".gif"
|
||||
@@ -433,8 +445,13 @@ anim = @animate for n in 1:6
|
||||
m = [1, .5, -1, -5, -20, -25]
|
||||
M = [2, 4, 5, 10, 25, 30]
|
||||
fn = x -> (x-1)*(x-2)*(x-3)*(x-5)
|
||||
title = L"Graph of on $(%$(m[n]), %$(M[n]))$"
|
||||
|
||||
plt = plot(fn, m[n], M[n], size=fig_size, legend=false, linewidth=2, title ="Graph of on ($(m[n]), $(M[n]))")
|
||||
plt = plot(fn, m[n], M[n];
|
||||
size=fig_size,
|
||||
legend=false,
|
||||
linewidth=2,
|
||||
title=title)
|
||||
if n > 1
|
||||
plot!(plt, fn, m[n-1], M[n-1], color=:red, linewidth=4)
|
||||
end
|
||||
@@ -468,11 +485,20 @@ The following graphic illustrates the $4$ basic *overall* shapes that can result
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plot(; layout=4)
|
||||
plot!(x -> x^4, -3,3, legend=false, xticks=false, yticks=false, subplot=1, title="n = even, aₙ > 0")
|
||||
plot!(x -> x^5, -3,3, legend=false, xticks=false, yticks=false, subplot=2, title="n = odd, aₙ > 0")
|
||||
plot!(x -> -x^4, -3,3, legend=false, xticks=false, yticks=false, subplot=3, title="n = even, aₙ < 0")
|
||||
plot!(x -> -x^5, -3,3, legend=false, xticks=false, yticks=false, subplot=4, title="n = odd, aₙ < 0")
|
||||
let
|
||||
gr()
|
||||
plot(; layout=4)
|
||||
plot!(x -> x^4, -3,3, legend=false, xticks=false, yticks=false, subplot=1, title=L"$n = $ even, $a_n > 0$")
|
||||
plot!(x -> x^5, -3,3, legend=false, xticks=false, yticks=false, subplot=2, title=L"$n = $ odd, $a_m > 0$")
|
||||
plot!(x -> -x^4, -3,3, legend=false, xticks=false, yticks=false, subplot=3, title=L"$n = $ even, $a_n < 0$")
|
||||
plot!(x -> -x^5, -3,3, legend=false, xticks=false, yticks=false, subplot=4, title=L"$n = $ odd, $a_n < 0$")
|
||||
end
|
||||
```
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
##### Example
|
||||
@@ -513,14 +539,15 @@ This observation is the start of Descartes' rule of [signs](http://sepwww.stanfo
|
||||
Among numerous others, there are two common ways of representing a non-zero polynomial:
|
||||
|
||||
|
||||
* expanded form, as in $a_n x^n + a_{n-1}x^{n-1} + \cdots + a_1 x + a_0, a_n \neq 0$; or
|
||||
* factored form, as in $a\cdot(x-r_1)\cdot(x-r_2)\cdots(x-r_n), a \neq 0$.
|
||||
* expanded form, as in $a_n x^n + a_{n-1}x^{n-1} + \cdots + a_1 x + a_0,\quad a_n \neq 0$; or
|
||||
* factored form, as in $a\cdot(x-r_1)\cdot(x-r_2)\cdots(x-r_n), \quad a \neq 0$.
|
||||
|
||||
|
||||
The former uses the *standard basis* to represent the polynomial $p$.
|
||||
The latter writes $p$ as a product of linear factors, though this is only possible in general if we consider complex roots. With real roots only, then the factors are either linear or quadratic, as will be discussed later.
|
||||
|
||||
|
||||
There are values to each representation. One value of the expanded form is that polynomial addition and scalar multiplication is much easier than in factored form. For example, adding polynomials just requires matching up the monomials of similar powers. For the factored form, polynomial multiplication is much easier than expanded form. For the factored form it is easy to read off *roots* of the polynomial (values of $x$ where $p$ is $0$), as a product is $0$ only if a term is $0$, so any zero must be a zero of a factor. Factored form has other technical advantages. For example, the polynomial $(x-1)^{1000}$ can be compactly represented using the factored form, but would require $1001$ coefficients to store in expanded form. (As well, due to floating point differences, the two would evaluate quite differently as one would require over a $1000$ operations to compute, the other just two.)
|
||||
There are values to each representation. One value of the expanded form is that polynomial addition and scalar multiplication is much easier than in factored form. For example, adding polynomials just requires matching up the monomials of similar powers. (These can be realized easily as vector operations.) For the factored form, polynomial multiplication is much easier than expanded form. For the factored form it is easy to read off *roots* of the polynomial (values of $x$ where $p$ is $0$), as a product is $0$ only if a term is $0$, so any zero must be a zero of a factor. Factored form has other technical advantages. For example, the polynomial $(x-1)^{1000}$ can be compactly represented using the factored form, but would require $1001$ coefficients to store in expanded form. (As well, due to floating point differences, the two would evaluate quite differently as one would require over a $1000$ operations to compute, the other just two.)
|
||||
|
||||
|
||||
Translating from factored form to expanded form can be done by carefully following the distributive law of multiplication. For example, with some care it can be shown that:
|
||||
@@ -587,7 +614,7 @@ It is easy to create a symbolic expression from a function - just evaluate the f
|
||||
f(x)
|
||||
```
|
||||
|
||||
This is easy - but can also be confusing. The function object is `f`, the expression is `f(x)` - the function evaluated on a symbolic object. Moreover, as seen, the symbolic expression can be evaluated using the same syntax as a function call:
|
||||
This is easy--but can also be confusing. The function object is `f`, the expression is `f(x)`--the function evaluated on a symbolic object. Moreover, as seen, the symbolic expression can be evaluated using the same syntax as a function call:
|
||||
|
||||
|
||||
```{julia}
|
||||
|
||||
@@ -453,7 +453,7 @@ N.(solveset(p ~ 0, x))
|
||||
## Do numeric methods matter when you can just graph?
|
||||
|
||||
|
||||
It may seem that certain practices related to roots of polynomials are unnecessary as we could just graph the equation and look for the roots. This feeling is perhaps motivated by the examples given in textbooks to be worked by hand, which necessarily focus on smallish solutions. But, in general, without some sense of where the roots are, an informative graph itself can be hard to produce. That is, technology doesn't displace thinking - it only supplements it.
|
||||
It may seem that certain practices related to roots of polynomials are unnecessary as we could just graph the equation and look for the roots. This feeling is perhaps motivated by the examples given in textbooks to be worked by hand, which necessarily focus on smallish solutions. But, in general, without some sense of where the roots are, an informative graph itself can be hard to produce. That is, technology doesn't displace thinking--it only supplements it.
|
||||
|
||||
|
||||
For another example, consider the polynomial $(x-20)^5 - (x-20) + 1$. In this form we might think the roots are near $20$. However, were we presented with this polynomial in expanded form: $x^5 - 100x^4 + 4000x^3 - 80000x^2 + 799999x - 3199979$, we might be tempted to just graph it to find roots. A naive graph might be to plot over $[-10, 10]$:
|
||||
@@ -553,7 +553,7 @@ N.(solve(j ~ 0, x))
|
||||
### Cauchy's bound on the magnitude of the real roots.
|
||||
|
||||
|
||||
Descartes' rule gives a bound on how many real roots there may be. Cauchy provided a bound on how large they can be. Assume our polynomial is monic (if not, divide by $a_n$ to make it so, as this won't effect the roots). Then any real root is no larger in absolute value than $|a_0| + |a_1| + |a_2| + \cdots + |a_{n-1}| + 1$, (this is expressed in different ways.)
|
||||
Descartes' rule gives a bound on how many real roots there may be. Cauchy provided a bound on how large they can be. Assume our polynomial is monic (if not, divide by $a_n$ to make it so, as this won't effect the roots). Then any real root is no larger in absolute value than $h = 1 + |a_0| + |a_1| + |a_2| + \cdots + |a_{n-1}|$, (this is expressed in different ways.)
|
||||
|
||||
|
||||
To see precisely [why](https://captainblack.wordpress.com/2009/03/08/cauchys-upper-bound-for-the-roots-of-a-polynomial/) this bound works, suppose $x$ is a root with $|x| > 1$ and let $h$ be the bound. Then since $x$ is a root, we can solve $a_0 + a_1x + \cdots + 1 \cdot x^n = 0$ for $x^n$ as:
|
||||
@@ -563,7 +563,7 @@ $$
|
||||
x^n = -(a_0 + a_1 x + \cdots a_{n-1}x^{n-1})
|
||||
$$
|
||||
|
||||
Which after taking absolute values of both sides, yields:
|
||||
Which after taking absolute values of both sides, yields by the triangle inequality:
|
||||
|
||||
|
||||
$$
|
||||
|
||||
@@ -18,7 +18,7 @@ import SymPy # imported only: some functions, e.g. degree, need qualification
|
||||
---
|
||||
|
||||
|
||||
While `SymPy` can be used to represent polynomials, there are also native `Julia` packages available for this and related tasks. These packages include `Polynomials`, `MultivariatePolynomials`, and `AbstractAlgebra`, among many others. (A search on [juliahub.com](juliahub.com) found over $50$ packages matching "polynomial".) We will look at the `Polynomials` package in the following, as it is straightforward to use and provides the features we are looking at for univariate polynomials.
|
||||
While `SymPy` can be used to represent polynomials, there are also native `Julia` packages available for this and related tasks. These packages include `Polynomials`, `MultivariatePolynomials`, and `AbstractAlgebra`, among many others. (A search on [juliahub.com](https://juliahub.com) found almost $100$ packages matching "polynomial".) We will look at the `Polynomials` package in the following, as it is straightforward to use and provides the features we are looking at for *univariate* polynomials.
|
||||
|
||||
|
||||
## Construction
|
||||
@@ -76,7 +76,7 @@ Polynomials may be evaluated using function notation, that is:
|
||||
p(1)
|
||||
```
|
||||
|
||||
This blurs the distinction between a polynomial expression – a formal object consisting of an indeterminate, coefficients, and the operations of addition, subtraction, multiplication, and non-negative integer powers – and a polynomial function.
|
||||
This blurs the distinction between a polynomial expression--a formal object consisting of an indeterminate, coefficients, and the operations of addition, subtraction, multiplication, and non-negative integer powers--and a polynomial function.
|
||||
|
||||
|
||||
The polynomial variable, in this case `1x`, can be returned by `variable`:
|
||||
@@ -86,14 +86,15 @@ The polynomial variable, in this case `1x`, can be returned by `variable`:
|
||||
x = variable(p)
|
||||
```
|
||||
|
||||
This variable is a `Polynomial` object, so can be manipulated as a polynomial; we can then construct polynomials through expressions like:
|
||||
This variable is a `Polynomial` object that prints as `x`.
|
||||
These variables can be manipulated as any polynomial. We can then construct polynomials through expressions like:
|
||||
|
||||
|
||||
```{julia}
|
||||
r = (x-2)^2 * (x-1) * (x+1)
|
||||
```
|
||||
|
||||
The product is expanded for storage by `Polynomials`, which may not be desirable for some uses. A new variable can be produced by calling `variable()`; so we could have constructed `p` by:
|
||||
The product is expanded for storage by `Polynomials`, which may not be desirable for some uses. A new variable can also be produced by calling `variable()`; so we could have constructed `p` by:
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -125,7 +126,7 @@ The `Polynomials` package has different ways to represent polynomials, and a fac
|
||||
fromroots(FactoredPolynomial, [2, 2, 1, -1])
|
||||
```
|
||||
|
||||
This form is helpful for some operations, for example polynomial multiplication and positive integer exponentiation, but not others such as addition of polynomials, where such polynomials must first be converted to the standard basis to add and are then converted back into a factored form.
|
||||
This form is helpful for some operations, for example polynomial multiplication and positive integer exponentiation, but not others such as addition of polynomials, where such polynomials must first be converted to the standard basis to add and are then converted back into a factored form. (A task that may suffer from floating point roundoff.)
|
||||
|
||||
|
||||
---
|
||||
@@ -181,7 +182,7 @@ A consequence of the fundamental theorem of algebra and the factor theorem is th
|
||||
|
||||
:::{.callout-note}
|
||||
## Note
|
||||
`SymPy` also has a `roots` function. If both `Polynomials` and `SymPy` are used together, calling `roots` must be qualified, as with `Polynomials.roots(...)`. Similarly, `degree` is provided in both, so it too must be qualified.
|
||||
`SymPy` also has a `roots` function. If both `Polynomials` and `SymPy` are used together, calling `roots` must be qualified, as with `Polynomials.roots(...)`. Similarly, `degree` is exported in both, so it too must be qualified.
|
||||
|
||||
:::
|
||||
|
||||
|
||||
@@ -103,13 +103,13 @@ h = (b-a)/(n-1)
|
||||
collect(a:h:b)
|
||||
```
|
||||
|
||||
Pretty neat. If we were doing this many times - such as once per plot - we'd want to encapsulate this into a function, for example:
|
||||
Pretty neat. If we were doing this many times - such as once per plot - we'd want to encapsulate this into a function, for example using a comprehension:
|
||||
|
||||
|
||||
```{julia}
|
||||
function evenly_spaced(a, b, n)
|
||||
h = (b-a)/(n-1)
|
||||
collect(a:h:b)
|
||||
[a + i*h for i in 0:n-1]
|
||||
end
|
||||
```
|
||||
|
||||
@@ -131,10 +131,10 @@ It seems to work as expected. But looking just at the algorithm it isn't quite s
|
||||
|
||||
|
||||
```{julia}
|
||||
1/5 + 2*1/5 # last value
|
||||
1/5 + 2*1/5 # last value if h is exactly 1/5 or 0.2
|
||||
```
|
||||
|
||||
Floating point roundoff leads to the last value *exceeding* `0.6`, so should it be included? Well, here it is pretty clear it *should* be, but better to have something programmed that hits both `a` and `b` and adjusts `h` accordingly.
|
||||
Floating point roundoff leads to the last value *exceeding* `0.6`, so should it be included? Well, here it is pretty clear it *should* be, but better to have something programmed that hits both `a` and `b` and adjusts `h` accordingly. Something which isn't subject to the vagaries of `(3/5 - 1/5)/2` not being `0.2`.
|
||||
|
||||
|
||||
Enter the base function `range` which solves this seemingly simple - but not really - task. It can use `a`, `b`, and `n`. Like the range operation, this function returns a generator which can be collected to realize the values.
|
||||
@@ -144,14 +144,7 @@ The number of points is specified as a third argument (though keyword arguments
|
||||
|
||||
|
||||
```{julia}
|
||||
xs = range(-1, 1,9)
|
||||
```
|
||||
|
||||
and
|
||||
|
||||
|
||||
```{julia}
|
||||
collect(xs)
|
||||
xs = range(1/5, 3/5, 3) |> collect
|
||||
```
|
||||
|
||||
:::{.callout-note}
|
||||
@@ -266,7 +259,7 @@ Here are decreasing powers of $2$:
|
||||
[1/2^i for i in 1:10]
|
||||
```
|
||||
|
||||
Sometimes, the comprehension does not produce the type of output that may be expected. This is related to `Julia`'s more limited abilities to infer types at the command line. If the output type is important, the extra prefix of `T[]` can be used, where `T` is the desired type. We will see that this will be needed at times with symbolic math.
|
||||
Sometimes, the comprehension does not produce the type of output that may be expected. This is related to `Julia`'s more limited abilities to infer types at the command line. If the output type is important, the extra prefix of `T[]` can be used, where `T` is the desired type.
|
||||
|
||||
|
||||
### Generators
|
||||
|
||||
@@ -15,7 +15,7 @@ import Polynomials
|
||||
using RealPolynomialRoots
|
||||
```
|
||||
|
||||
The `Polynomials` package is "imported" to avoid naming collisions with `SymPy`; names will need to be qualified.
|
||||
The `Polynomials` package is "imported" to avoid naming collisions with `SymPy`;some names may need to be qualified.
|
||||
|
||||
|
||||
|
||||
@@ -410,7 +410,7 @@ The usual recipe for construction follows these steps:
|
||||
* Identify "test points" within each implied interval (these are $(-\infty, -1)$, $(-1,0)$, $(0,1)$, and $(1, \infty)$ in the example) and check for the sign of $f(x)$ at these test points. Write in `-`, `+`, `0`, or `*`, as appropriate. The value comes from the fact that "continuous" functions may only change sign when they cross $0$ or are undefined.
|
||||
|
||||
|
||||
With the computer, where it is convenient to draw a graph, it might be better to emphasize the sign on the graph of the function. The `sign_chart` function from `CalculusWithJulia` does this by numerically identifying points where the function is $0$ or $\infty$ and indicating the sign as $x$ crosses over these points.
|
||||
With the computer, where it is convenient to draw a graph, it might be better to emphasize the sign on the graph of the function, but at times numeric values are preferred. The `sign_chart` function from `CalculusWithJulia` does this analysis by numerically identifying points where the function is $0$ or $\infty$ and indicating the sign as $x$ crosses over these points.
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -419,6 +419,8 @@ f(x) = x^3 - x
|
||||
sign_chart(f, -3/2, 3/2)
|
||||
```
|
||||
|
||||
This format is a bit different from above, but shows to the left of $-1$ a minussign; between $-1$ and $0$ a plus sign; between $0$ and $1$ a minus sign; and between $1$ and $3/2$ a plus sign.
|
||||
|
||||
## Pade approximate
|
||||
|
||||
|
||||
|
||||
@@ -220,7 +220,7 @@ Scaling by $2$ shrinks the non-zero domain, scaling by $1/2$ would stretch it. I
|
||||
---
|
||||
|
||||
|
||||
More exciting is what happens if we combine these operations.
|
||||
More exciting is what happens if we compose these operations.
|
||||
|
||||
|
||||
A shift right by $2$ and up by $1$ is achieved through
|
||||
@@ -267,7 +267,7 @@ We can view this as a composition of "scale" by $1/a$, then "over" by $b$, and
|
||||
#| hold: true
|
||||
a = 2; b = 5
|
||||
h(x) = stretch(over(scale(f, 1/a), b), 1/a)(x)
|
||||
plot(f, -1, 8, label="f")
|
||||
plot(f, -1, 8, label="f"; xticks=-1:8)
|
||||
plot!(h, label="h")
|
||||
```
|
||||
|
||||
|
||||
@@ -34,12 +34,37 @@ For a right triangle with angles $\theta$, $\pi/2 - \theta$, and $\pi/2$ ($0 < \
|
||||
```{julia}
|
||||
#| hide: true
|
||||
#| echo: false
|
||||
p = plot(legend=false, xlim=(-1/4,5), ylim=(-1/2, 3),
|
||||
xticks=nothing, yticks=nothing, border=:none)
|
||||
plot!([0,4,4,0],[0,0,3,0], linewidth=3)
|
||||
del = .25
|
||||
plot!([4-del, 4-del,4], [0, del, del], color=:black, linewidth=3)
|
||||
annotate!([(.75, .25, "θ"), (4.0, 1.25, "opposite"), (2, -.25, "adjacent"), (1.5, 1.25, "hypotenuse")])
|
||||
let
|
||||
gr()
|
||||
p = plot(;legend=false,
|
||||
xticks=nothing, yticks=nothing,
|
||||
border=:none,
|
||||
xlim=(-1/4,5), ylim=(-1/2, 3))
|
||||
plot!([0,4,4,0],[0,0,3,0], linewidth=3)
|
||||
θ = atand(3,4)
|
||||
del = .25
|
||||
plot!([4-del, 4-del,4], [0, del, del], color=:black, linewidth=3)
|
||||
theta = pi/20
|
||||
r = sqrt((3/4)^2 + (1/4)^2)
|
||||
ts = range(0, theta, 20)
|
||||
plot!(r*cos.(ts), r*sin.(ts); line=(:gray, 1))
|
||||
ts = range(atan(3/4) - theta, atan(3,4), 20)
|
||||
plot!(r*cos.(ts), r*sin.(ts); line=(:gray, 1))
|
||||
|
||||
annotate!([
|
||||
(.75, .25, L"\theta"),
|
||||
(4.0, 1.5+.1, text("opposite", rotation=90,:top)),
|
||||
(2, -.25, "adjacent"),
|
||||
(2, 1.5+.1, text("hypotenuse", rotation=θ,:bottom))
|
||||
])
|
||||
|
||||
end
|
||||
```
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
With these, the basic definitions for the primary trigonometric functions are
|
||||
@@ -77,9 +102,13 @@ gr()
|
||||
|
||||
function plot_angle(m)
|
||||
r = m*pi
|
||||
n,d = numerator(m), denominator(m)
|
||||
|
||||
ts = range(0, stop=2pi, length=100)
|
||||
tit = "$m ⋅ pi -> ($(round(cos(r), digits=2)), $(round(sin(r), digits=2)))"
|
||||
tit = latexstring("\\frac{$n}{$d}") *
|
||||
L"\cdot\pi\rightarrow (" *
|
||||
latexstring("$(round(cos(r), digits=2)),$(round(sin(r), digits=2)))")
|
||||
|
||||
ts = range(0, 2pi, 151)
|
||||
p = plot(cos.(ts), sin.(ts), legend=false, aspect_ratio=:equal,title=tit)
|
||||
plot!(p, [-1,1], [0,0], color=:gray30)
|
||||
plot!(p, [0,0], [-1,1], color=:gray30)
|
||||
@@ -95,13 +124,11 @@ function plot_angle(m)
|
||||
plot!(p, [0,l*cos(r)], [0,l*sin(r)], color=:green, linewidth=4)
|
||||
|
||||
scatter!(p, [cos(r)], [sin(r)], markersize=5)
|
||||
annotate!(p, [(1/4+cos(r), sin(r), "(x,y)")])
|
||||
annotate!(p, [(1/4+cos(r), sin(r), L"(x,y)")])
|
||||
|
||||
p
|
||||
end
|
||||
|
||||
|
||||
|
||||
## different linear graphs
|
||||
anim = @animate for m in -4//3:1//6:10//3
|
||||
plot_angle(m)
|
||||
@@ -406,7 +433,7 @@ Suppose both $\alpha$ and $\beta$ are positive with $\alpha + \beta \leq \pi/2$.
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
|
||||
gr()
|
||||
using Plots, LaTeXStrings
|
||||
|
||||
# two angles
|
||||
@@ -425,7 +452,10 @@ color1 = :royalblue
|
||||
color2 = :forestgreen
|
||||
color3 = :brown3
|
||||
color4 = :mediumorchid2
|
||||
canvas() = plot(axis=([],false), legend=false, aspect_ratio=:equal)
|
||||
canvas() = plot(;
|
||||
axis=([],false),
|
||||
legend=false,
|
||||
aspect_ratio=:equal)
|
||||
p1 = canvas()
|
||||
plot!(Shape([A,B,F]), fill=(color4, 0.15))
|
||||
|
||||
@@ -440,29 +470,29 @@ ddf = sqrt(sum((D.-F).^2))
|
||||
Δ = 0.0
|
||||
|
||||
alphabeta = (r*cos(α/2 + β/2), r*sin(α/2 + β/2),
|
||||
text("α + β",:hcenter; rotation=pi/2))
|
||||
cosαβ = (B[1]/2, 0, text("cos(α + β)", :top))
|
||||
sinαβ = (B[1], F[2]/2, text("sin(α + β)"))
|
||||
text(L"\alpha + \beta",:left, rotation=pi/2))
|
||||
cosαβ = (B[1]/2, 0, text(L"\cos(\alpha + \beta)", :top))
|
||||
sinαβ = (B[1], F[2]/2, text(L"\sin(\alpha + \beta)", rotation=90,:top))
|
||||
|
||||
txtpoints = (
|
||||
one = (F[1]/2, F[2]/2, "1",:right),
|
||||
one = (F[1]/2, F[2]/2, text(L"1", :bottom)),
|
||||
beta=(r*cos(α + β/2), r*sin(α + β/2),
|
||||
text("β", :hcenter)),
|
||||
text(L"\beta", :hcenter)),
|
||||
alpha = (r*cos(α/2), r*sin(α/2),
|
||||
text("α",:hcenter)),
|
||||
text(L"\alpha",:hcenter)),
|
||||
alphaa = (F[1] + r*sin(α/2), F[2] - r*cos(α/2) ,
|
||||
text("α"),:hcenter),
|
||||
text(L"\alpha"),:hcenter),
|
||||
cosβ = (dae/2*cos(α),dae/2*sin(α) + Δ,
|
||||
text("cos(β)",:hcenter)),
|
||||
text(L"\cos(\beta)",:bottom, rotation=rad2deg(α))),
|
||||
sinβ = (B[1] + dbc/2 + Δ/2, D[2] + ddf/2 + Δ/2,
|
||||
text("sin(β)",:bottom)),
|
||||
cosαcosβ = (C[1]/2, 0 - Δ, text("cos(α)cos(β)", :top)),
|
||||
sinαcosβ = (cos(α)*cos(β) - 0.1, dce/2 ,
|
||||
text("sin(α)cos(β)", :hcenter)),
|
||||
text(L"\sin(\beta)",:bottom, rotation=-(90-rad2deg(α)))),
|
||||
cosαcosβ = (C[1]/2, 0 - Δ, text(L"\cos(\alpha)\cos(\beta)", :top)),
|
||||
sinαcosβ = (cos(α)*cos(β), dce/2 ,
|
||||
text(L"\sin(\alpha)\cos(\beta)", :top, rotation=90)),
|
||||
cosαsinβ = (D[1] - Δ, D[2] + ddf/2 ,
|
||||
text("cos(α)sin(β)", :top)),
|
||||
text(L"\cos(\alpha)\sin(\beta)", :bottom, 10, rotation=90)),
|
||||
sinαsinβ = (D[1] + dde/2, D[2] + Δ ,
|
||||
text("sin(α)sin(β)", :top)),
|
||||
text(L"\sin(\alpha)\sin(\beta)", 10, :top)),
|
||||
)
|
||||
|
||||
# Plot 1
|
||||
@@ -574,6 +604,12 @@ $$
|
||||
$$
|
||||
:::
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
##### Example
|
||||
|
||||
|
||||
@@ -1028,4 +1064,3 @@ Is this identical to the pattern for the regular sine function?
|
||||
#| echo: false
|
||||
yesnoq(false)
|
||||
```
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
|
||||
# Vectors
|
||||
# Vectors and containers
|
||||
|
||||
|
||||
{{< include ../_common_code.qmd >}}
|
||||
@@ -143,8 +142,9 @@ We call the values $x$ and $y$ of the vector $\vec{v} = \langle x,~ y \rangle$ t
|
||||
Two operations on vectors are fundamental.
|
||||
|
||||
|
||||
* Vectors can be multiplied by a scalar (a real number): $c\vec{v} = \langle cx,~ cy \rangle$. Geometrically this scales the vector by a factor of $\lvert c \rvert$ and switches the direction of the vector by $180$ degrees (in the $2$-dimensional case) when $c < 0$. A *unit vector* is one with magnitude $1$, and, except for the $\vec{0}$ vector, can be formed from $\vec{v}$ by dividing $\vec{v}$ by its magnitude. A vector's two parts are summarized by its direction given by a unit vector **and** its magnitude given by the norm.
|
||||
* Vectors can be added: $\vec{v} + \vec{w} = \langle v_x + w_x,~ v_y + w_y \rangle$. That is, each corresponding component adds to form a new vector. Similarly for subtraction. The $\vec{0}$ vector then would be just $\langle 0,~ 0 \rangle$ and would satisfy $\vec{0} + \vec{v} = \vec{v}$ for any vector $\vec{v}$. Vector addition, $\vec{v} + \vec{w}$, is visualized by placing the tail of $\vec{w}$ at the tip of $\vec{v}$ and then considering the new vector with tail coming from $\vec{v}$ and tip coming from the position of the tip of $\vec{w}$. Subtraction is different, place both the tails of $\vec{v}$ and $\vec{w}$ at the same place and the new vector has tail at the tip of $\vec{w}$ and tip at the tip of $\vec{v}$.
|
||||
* *Scalar multiplication*: Vectors can be multiplied by a scalar (a real number): $c\vec{v} = \langle cx,~ cy \rangle$. Geometrically this scales the vector by a factor of $\lvert c \rvert$ and switches the direction of the vector by $180$ degrees (in the $2$-dimensional case) when $c < 0$. A *unit vector* is one with magnitude $1$, and, except for the $\vec{0}$ vector, can be formed from $\vec{v}$ by dividing $\vec{v}$ by its magnitude. A vector's two parts are summarized by its direction given by a unit vector **and** its magnitude given by the norm.
|
||||
|
||||
* *Vector addition*: Vectors can be added: $\vec{v} + \vec{w} = \langle v_x + w_x,~ v_y + w_y \rangle$. That is, each corresponding component adds to form a new vector. Similarly for subtraction. The $\vec{0}$ vector then would be just $\langle 0,~ 0 \rangle$ and would satisfy $\vec{0} + \vec{v} = \vec{v}$ for any vector $\vec{v}$. Vector addition, $\vec{v} + \vec{w}$, is visualized by placing the tail of $\vec{w}$ at the tip of $\vec{v}$ and then considering the new vector with tail coming from $\vec{v}$ and tip coming from the position of the tip of $\vec{w}$. Subtraction is different, place both the tails of $\vec{v}$ and $\vec{w}$ at the same place and the new vector has tail at the tip of $\vec{w}$ and tip at the tip of $\vec{v}$.
|
||||
|
||||
|
||||
```{julia}
|
||||
@@ -334,7 +334,7 @@ Finally, to find an angle $\theta$ from a vector $\langle x,~ y\rangle$, we can
|
||||
norm(v), atan(y, x) # v = [x, y]
|
||||
```
|
||||
|
||||
## Higher dimensional vectors
|
||||
### Higher dimensional vectors
|
||||
|
||||
|
||||
Mathematically, vectors can be generalized to more than $2$ dimensions. For example, using $3$-dimensional vectors are common when modeling events happening in space, and $4$-dimensional vectors are common when modeling space and time.
|
||||
@@ -395,334 +395,6 @@ Whereas, in this example where there is no common type to promote the values to,
|
||||
["one", 2, 3.0, 4//1]
|
||||
```
|
||||
|
||||
## Indexing
|
||||
|
||||
|
||||
Getting the components out of a vector can be done in a manner similar to multiple assignment:
|
||||
|
||||
|
||||
```{julia}
|
||||
vs = [1, 2]
|
||||
v₁, v₂ = vs
|
||||
```
|
||||
|
||||
When the same number of variable names are on the left hand side of the assignment as in the container on the right, each is assigned in order.
|
||||
|
||||
|
||||
Though this is convenient for small vectors, it is far from being so if the vector has a large number of components. However, the vector is stored in order with a first, second, third, $\dots$ component. `Julia` allows these values to be referred to by *index*. This too uses the `[]` notation, though differently. Here is how we get the second component of `vs`:
|
||||
|
||||
|
||||
```{julia}
|
||||
vs[2]
|
||||
```
|
||||
|
||||
The last value of a vector is usually denoted by $v_n$. In `Julia`, the `length` function will return $n$, the number of items in the container. So `v[length(v)]` will refer to the last component. However, the special keyword `end` will do so as well, when put into the context of indexing. So `v[end]` is more idiomatic. (Similarly, there is a `begin` keyword that is useful when the vector is not $1$-based, as is typical but not mandatory.)
|
||||
|
||||
The functions `first` and `last` refer to the first and last components of a collection. An additional argument can be specified to take the first (or last) $n$ components. The function `only` will return the only component of a vector, if it has length $1$ and error otherwise.
|
||||
|
||||
|
||||
:::{.callout-note}
|
||||
## More on indexing
|
||||
There is [much more](https://docs.julialang.org/en/v1/manual/arrays/#man-array-indexing) to indexing than just indexing by a single integer value. For example, the following can be used for indexing:
|
||||
|
||||
* a scalar integer (as seen)
|
||||
* a range
|
||||
* a vector of integers
|
||||
* a boolean vector
|
||||
|
||||
:::
|
||||
|
||||
Some add-on packages extend this further.
|
||||
|
||||
|
||||
### Assignment and indexing
|
||||
|
||||
|
||||
Indexing notation can also be used with assignment, meaning it can appear on the left hand side of an equals sign. The following expression replaces the second component with a new value:
|
||||
|
||||
|
||||
```{julia}
|
||||
vs[2] = 10
|
||||
```
|
||||
|
||||
The value of the right hand side is returned, not the value for `vs`. We can check that `vs` is then $\langle 1,~ 10 \rangle$ by showing it:
|
||||
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
vs = [1,2]
|
||||
vs[2] = 10
|
||||
vs
|
||||
```
|
||||
|
||||
The assignment `vs[2]` is different than the initial assignment `vs=[1,2]` in that, `vs[2]=10` **modifies** the container that `vs` points to, whereas `vs=[1,2]` **replaces** any binding for `vs`. The indexed assignment is more memory efficient when vectors are large. This point is also of interest when passing vectors to functions, as a function may modify components of the vector passed to it, though can't replace the container itself.
|
||||
|
||||
|
||||
## Some useful functions for working with vectors.
|
||||
|
||||
|
||||
As mentioned, the `length` function returns the number of components in a vector. It is one of several useful functions for vectors.
|
||||
|
||||
|
||||
The `sum` and `prod` function will add and multiply the elements in a vector:
|
||||
|
||||
|
||||
```{julia}
|
||||
v1 = [1,1,2,3,5,8]
|
||||
sum(v1), prod(v1)
|
||||
```
|
||||
|
||||
The `unique` function will throw out any duplicates:
|
||||
|
||||
|
||||
```{julia}
|
||||
unique(v1) # drop a `1`
|
||||
```
|
||||
|
||||
The functions `maximum` and `minimum` will return the largest and smallest values of an appropriate vector.
|
||||
|
||||
|
||||
```{julia}
|
||||
maximum(v1)
|
||||
```
|
||||
|
||||
(These should not be confused with `max` and `min` which give the largest or smallest value over all their arguments.)
|
||||
|
||||
|
||||
The `extrema` function returns both the smallest and largest value of a collection:
|
||||
|
||||
|
||||
```{julia}
|
||||
extrema(v1)
|
||||
```
|
||||
|
||||
Consider now
|
||||
|
||||
|
||||
```{julia}
|
||||
𝒗 = [1,4,2,3]
|
||||
```
|
||||
|
||||
The `sort` function will rearrange the values in `𝒗`:
|
||||
|
||||
|
||||
```{julia}
|
||||
sort(𝒗)
|
||||
```
|
||||
|
||||
The keyword argument, `rev=true` can be given to get values in decreasing order:
|
||||
|
||||
|
||||
```{julia}
|
||||
sort(𝒗, rev=true)
|
||||
```
|
||||
|
||||
For adding a new element to a vector the `push!` method can be used, as in
|
||||
|
||||
|
||||
```{julia}
|
||||
push!(𝒗, 5)
|
||||
```
|
||||
|
||||
To append more than one value, the `append!` function can be used:
|
||||
|
||||
|
||||
```{julia}
|
||||
append!(v1, [6,8,7])
|
||||
```
|
||||
|
||||
These two functions modify or mutate the values stored within the vector `𝒗` that passed as an argument. In the `push!` example above, the value `5` is added to the vector of $4$ elements. In `Julia`, a convention is to name mutating functions with a trailing exclamation mark. (Again, these do not mutate the binding of `𝒗` to the container, but do mutate the contents of the container.) There are functions with mutating and non-mutating definitions, an example is `sort` and `sort!`.
|
||||
|
||||
|
||||
If only a mutating function is available, like `push!`, and this is not desired a copy of the vector can be made. It is not enough to copy by assignment, as with `w = 𝒗`. As both `w` and `𝒗` will be bound to the same memory location. Rather, you call `copy` (or sometimes `deepcopy`) to make a new container with copied contents, as in `w = copy(𝒗)`.
|
||||
|
||||
|
||||
Creating new vectors of a given size is common for programming, though not much use will be made here. There are many different functions to do so: `ones` to make a vector of ones, `zeros` to make a vector of zeros, `trues` and `falses` to make Boolean vectors of a given size, and `similar` to make a similar-sized vector (with no particular values assigned).
|
||||
|
||||
|
||||
## Applying functions element by element to values in a vector
|
||||
|
||||
|
||||
Functions such as `sum` or `length` are known as *reductions* as they reduce the "dimensionality" of the data: a vector is in some sense $1$-dimensional, the sum or length are $0$-dimensional numbers. Applying a reduction is straightforward – it is just a regular function call.
|
||||
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
v = [1, 2, 3, 4]
|
||||
sum(v), length(v)
|
||||
```
|
||||
|
||||
Other desired operations with vectors act differently. Rather than reduce a collection of values using some formula, the goal is to apply some formula to *each* of the values, returning a modified vector. A simple example might be to square each element, or subtract the average value from each element. An example comes from statistics. When computing a variance, we start with data $x_1, x_2, \dots, x_n$ and along the way form the values $(x_1-\bar{x})^2, (x_2-\bar{x})^2, \dots, (x_n-\bar{x})^2$.
|
||||
|
||||
|
||||
Such things can be done in *many* different ways. Here we describe two, but will primarily utilize the first.
|
||||
|
||||
|
||||
### Broadcasting a function call
|
||||
|
||||
|
||||
If we have a vector, `xs`, and a function, `f`, to apply to each value, there is a simple means to achieve this task. By adding a "dot" between the function name and the parenthesis that enclose the arguments, instructs `Julia` to "broadcast" the function call. The details allow for more flexibility, but, for this purpose, broadcasting will take each value in `xs` and apply `f` to it, returning a vector of the same size as `xs`. When more than one argument is involved, broadcasting will try to fill out different sized objects.
|
||||
|
||||
|
||||
For example, the following will find, using `sqrt`, the square root of each value in a vector:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs = [1, 1, 3, 4, 7]
|
||||
sqrt.(xs)
|
||||
```
|
||||
|
||||
This would find the sine of each number in `xs`:
|
||||
|
||||
|
||||
```{julia}
|
||||
sin.(xs)
|
||||
```
|
||||
|
||||
For each function, the `.(` (and not `(`) after the name is the surface syntax for broadcasting.
|
||||
|
||||
|
||||
The `^` operator is an *infix* operator. Infix operators can be broadcast, as well, by using the form `.` prior to the operator, as in:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs .^ 2
|
||||
```
|
||||
|
||||
Here is an example involving the logarithm of a set of numbers. In astronomy, a logarithm with base $100^{1/5}$ is used for star [brightness](http://tinyurl.com/ycp7k8ay). We can use broadcasting to find this value for several values at once through:
|
||||
|
||||
|
||||
```{julia}
|
||||
ys = [1/5000, 1/500, 1/50, 1/5, 5, 50]
|
||||
base = (100)^(1/5)
|
||||
log.(base, ys)
|
||||
```
|
||||
|
||||
Broadcasting with multiple arguments allows for mixing of vectors and scalar values, as above, making it convenient when parameters are used.
|
||||
|
||||
|
||||
As a final example, the task from statistics of centering and then squaring can be done with broadcasting. We go a bit further, showing how to compute the [sample variance](http://tinyurl.com/p6wa4r8) of a data set. This has the formula
|
||||
|
||||
|
||||
$$
|
||||
\frac{1}{n-1}\cdot ((x_1-\bar{x})^2 + \cdots + (x_n - \bar{x})^2).
|
||||
$$
|
||||
|
||||
This can be computed, with broadcasting, through:
|
||||
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
import Statistics: mean
|
||||
xs = [1, 1, 2, 3, 5, 8, 13]
|
||||
n = length(xs)
|
||||
(1/(n-1)) * sum(abs2.(xs .- mean(xs)))
|
||||
```
|
||||
|
||||
This shows many of the manipulations that can be made with vectors. Rather than write `.^2`, we follow the definition of `var` and chose the possibly more performant `abs2` function which, in general, efficiently finds $|x|^2$ for various number types. The `.-` uses broadcasting to subtract a scalar (`mean(xs)`) from a vector (`xs`). Without the `.`, this would error.
|
||||
|
||||
|
||||
:::{.callout-note}
|
||||
## Note
|
||||
The `map` function is very much related to broadcasting and similarly named functions are found in many different programming languages. (The "dot" broadcast is mostly limited to `Julia` and mirrors a similar usage of a dot in `MATLAB`.) For those familiar with other programming languages, using `map` may seem more natural. Its syntax is `map(f, xs)`.
|
||||
|
||||
:::
|
||||
|
||||
### Comprehensions
|
||||
|
||||
|
||||
In mathematics, set notation is often used to describe elements in a set.
|
||||
|
||||
|
||||
For example, the first $5$ cubed numbers can be described by:
|
||||
|
||||
|
||||
$$
|
||||
\{x^3: x \text{ in } 1, 2,\dots, 5\}
|
||||
$$
|
||||
|
||||
Comprehension notation is similar. The above could be created in `Julia` with:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs = [1,2,3,4,5]
|
||||
[x^3 for x in xs]
|
||||
```
|
||||
|
||||
Something similar can be done more succinctly:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs .^ 3
|
||||
```
|
||||
|
||||
However, comprehensions have a value when more complicated expressions are desired as they work with an expression of `xs`, and not a pre-defined or user-defined function.
|
||||
|
||||
|
||||
Another typical example of set notation might include a condition, such as, the numbers divisible by $7$ between $1$ and $100$. Set notation might be:
|
||||
|
||||
|
||||
$$
|
||||
\{x: \text{rem}(x, 7) = 0 \text{ for } x \text{ in } 1, 2, \dots, 100\}.
|
||||
$$
|
||||
|
||||
This would be read: "the set of $x$ such that the remainder on division by $7$ is $0$ for all x in $1, 2, \dots, 100$."
|
||||
|
||||
|
||||
In `Julia`, a comprehension can include an `if` clause to mirror, somewhat, the math notation. For example, the above would become (using `1:100` as a means to create the numbers $1,2,\dots, 100$, as will be described in an upcoming section):
|
||||
|
||||
|
||||
```{julia}
|
||||
[x for x in 1:100 if rem(x,7) == 0]
|
||||
```
|
||||
|
||||
Comprehensions can be a convenient means to describe a collection of numbers, especially when no function is defined, but the simplicity of the broadcast notation (just adding a judicious ".") leads to its more common use in these notes.
|
||||
|
||||
|
||||
##### Example: creating a "T" table for creating a graph
|
||||
|
||||
|
||||
The process of plotting a function is usually first taught by generating a "T" table: values of $x$ and corresponding values of $y$. These pairs are then plotted on a Cartesian grid and the points are connected with lines to form the graph. Generating a "T" table in `Julia` is easy: create the $x$ values, then create the $y$ values for each $x$.
|
||||
|
||||
|
||||
To be concrete, let's generate $7$ points to plot $f(x) = x^2$ over $[-1,1]$.
|
||||
|
||||
|
||||
The first task is to create the data. We will soon see more convenient ways to generate patterned data, but for now, we do this by hand:
|
||||
|
||||
|
||||
```{julia}
|
||||
a, b, n = -1, 1, 7
|
||||
d = (b-a) // (n-1)
|
||||
xs = [a, a+d, a+2d, a+3d, a+4d, a+5d, a+6d] # 7 points
|
||||
```
|
||||
|
||||
To get the corresponding $y$ values, we can use a compression (or define a function and broadcast):
|
||||
|
||||
|
||||
```{julia}
|
||||
ys = [x^2 for x in xs]
|
||||
```
|
||||
|
||||
Vectors can be compared together by combining them into a separate container, as follows:
|
||||
|
||||
|
||||
```{julia}
|
||||
[xs ys]
|
||||
```
|
||||
|
||||
(If there is a space between objects they are horizontally combined. In our construction of vectors using `[]` we used a comma for vertical combination. More generally we should use a `;` for vertical concatenation.)
|
||||
|
||||
|
||||
In the sequel, we will typically use broadcasting for this task using two steps: one to define a function the second to broadcast it.
|
||||
|
||||
|
||||
:::{.callout-note}
|
||||
## Note
|
||||
The style generally employed here is to use plural variable names for a collection of values, such as the vector of $y$ values and singular names when a single value is being referred to, leading to expressions like "`x in xs`".
|
||||
|
||||
:::
|
||||
|
||||
## Other container types
|
||||
|
||||
We end this section with some general comments that are for those interested in a bit more, but in general aren't needed to understand most all of what follows later.
|
||||
@@ -761,12 +433,16 @@ Tuples are fixed-length containers where there is no expectation or enforcement
|
||||
|
||||
While a vector is formed by placing comma-separated values within a `[]` pair (e.g., `[1,2,3]`), a tuple is formed by placing comma-separated values within a `()` pair. A tuple of length $1$ uses a convention of a trailing comma to distinguish it from a parenthesized expression (e.g. `(1,)` is a tuple, `(1)` is just the value `1`).
|
||||
|
||||
|
||||
Vectors and tuples can appear at the same time: a vector of tuples--each of length $n$--can be used in plotting to specify points.
|
||||
|
||||
:::{.callout-note}
|
||||
## Well, actually...
|
||||
Technically, the tuple is formed just by the use of commas, which separate different expressions. The parentheses are typically used, as they clarify the intent and disambiguate some usage. In a notebook interface, it is useful to just use commas to separate values to output, as typically the only the last command is displayed. This usage just forms a tuple of the values and displays that.
|
||||
|
||||
:::
|
||||
|
||||
#### Named tuples
|
||||
|
||||
There are *named tuples* where each component has an associated name. Like a tuple these can be indexed by number and unlike regular tuples also by name.
|
||||
|
||||
@@ -795,12 +471,14 @@ The values in a named tuple can be accessed using the "dot" notation:
|
||||
nt.x1
|
||||
```
|
||||
|
||||
Alternatively, the index notation -- using a *symbol* for the name -- can be used:
|
||||
Alternatively, the index notation--using a *symbol* for the name--can be used:
|
||||
|
||||
```{julia}
|
||||
nt[:x1]
|
||||
```
|
||||
|
||||
(Indexing is described a bit later, but it is a way to pull elements out of a collection.)
|
||||
|
||||
Named tuples are employed to pass parameters to functions. To find the slope, we could do:
|
||||
|
||||
```{julia}
|
||||
@@ -820,11 +498,15 @@ x1 - x0
|
||||
:::
|
||||
|
||||
|
||||
### Associative arrays
|
||||
### Pairs, associative arrays
|
||||
|
||||
Named tuples associate a name (in this case a symbol) to a value. More generally an associative array associates to each key a value, where the keys and values may be of different types.
|
||||
|
||||
The `pair` notation, `key => value`, is used to make one association. A *dictionary* is used to have a container of associations. For example, this constructs a simple dictionary associating a spelled out name with a numeric value:
|
||||
The `pair` notation, `key => value`, is used to make one association between the first and second value.
|
||||
|
||||
A *dictionary* is used to have a container of associations.
|
||||
|
||||
This example constructs a simple dictionary associating a spelled out name with a numeric value:
|
||||
|
||||
```{julia}
|
||||
d = Dict("one" => 1, "two" => 2, "three" => 3)
|
||||
@@ -842,7 +524,449 @@ d["two"]
|
||||
|
||||
Named tuples are associative arrays where the keys are restricted to symbols. There are other types of associative arrays, specialized cases of the `AbstractDict` type with performance benefits for specific use cases. In these notes, dictionaries appear as output in some function calls.
|
||||
|
||||
Unlike vectors and tuples, dictionaries are not currently supported by broadcasting. This causes no loss in usefulness, as the values can easily be iterated over, but the convenience of the dot notation is lost.
|
||||
Unlike vectors and tuples, dictionaries are not currently supported by broadcasting. (To be described in the next section.) This causes no loss in usefulness, as the values can easily be iterated over, but the convenience of the dot notation is lost.
|
||||
|
||||
|
||||
## The container interface in Julia
|
||||
|
||||
There are numerous generic functions for working across the many different types of containers. Some are specific to containers which can be modified, some to associative arrays. But it is expected for different container types to implement as many as possible. We list a few here for completeness. Only a few will be used in these notes.
|
||||
|
||||
### Indexing
|
||||
|
||||
Vectors have an implied order: first element, second, last, etc. Tuples do as well. Matrices have two orders: by a row-column pair or by linear order where the first column precedes the second etc. Arrays are similar in that they have a linear order and can be accessed by their individual dimensions.
|
||||
|
||||
To access an element in a vector, say the second, the underlying `getindex` function is used. This is rarely typed, as the `[` notation is used. This notation is used in a style similar to a function call, the indexes go between matching pairs.
|
||||
|
||||
For example, we create a vector, tuple, and matrix:
|
||||
|
||||
```{julia}
|
||||
v = [1,2,3,4]
|
||||
t = (1,2,3,4)
|
||||
m = [1 2; 3 4]
|
||||
```
|
||||
|
||||
The second element of each is accessed similarly:
|
||||
|
||||
```{julia}
|
||||
v[2], t[2], m[2]
|
||||
```
|
||||
|
||||
(All of `v`, `t`, and `m` have $1$-based indexing.)
|
||||
|
||||
There is special syntax to reference the last index when used within the square braces:
|
||||
|
||||
```{julia}
|
||||
v[end], t[end], m[end]
|
||||
```
|
||||
|
||||
The last element is also returned by `last`:
|
||||
|
||||
```{julia}
|
||||
last(v), last(t), last(m)
|
||||
```
|
||||
|
||||
These use `lastindex` behind the scenes. There is also a `firstindex` which is associated with the `first` method:
|
||||
|
||||
|
||||
```{julia}
|
||||
first(v), first(t), first(m)
|
||||
```
|
||||
|
||||
For indexing by a numeric index, a container of numbers may be used. Containers can be generated different ways, here we just use a vector to get the second and third elements:
|
||||
|
||||
```{julia}
|
||||
I = [2,3]
|
||||
v[I], t[I], m[I]
|
||||
```
|
||||
|
||||
When indexing by a vector, the value will not be a scalar, even if there is only one element indicated.
|
||||
|
||||
Indexing can also be done by a mask of Boolean values with a matching length. This following mask should do the same as indexing by `I` above:
|
||||
|
||||
```{julia}
|
||||
J = [false, true, true, false]
|
||||
v[J], t[J], m[J]
|
||||
```
|
||||
|
||||
For the matrix, values can be referenced by row/column values. The following will extract the second row, first column:
|
||||
|
||||
```{julia}
|
||||
m[2, 1]
|
||||
```
|
||||
|
||||
*If* a container has *only* one entry, then the `only` method will return that element (not within the container). Here we use a tuple to illustrate to emphasize the trailing comma in construction:
|
||||
|
||||
```{julia}
|
||||
s = ("one", )
|
||||
```
|
||||
|
||||
```{julia}
|
||||
only(s)
|
||||
```
|
||||
|
||||
There will be an error with `only` should the container not have just one element.
|
||||
|
||||
### Mutating values
|
||||
|
||||
Vectors and matrices can have their elements changed or mutated; tuples can not. The process is similar to assignment--using an equals sign--but the left hand side has indexing notation to reference which values within the container are to be updated.
|
||||
|
||||
To change the last element of `v` to `0` we have:
|
||||
|
||||
```{julia}
|
||||
v[end] = 0
|
||||
v
|
||||
```
|
||||
|
||||
We might read this as assignment, but what happens is the underlying container has an element indicated by the index mutated. The `setindex!` function is called behind the scenes.
|
||||
|
||||
|
||||
The `setindex!` function will try to promote the value (`0` above) to the element type of the container. This can throw an error if the promotion isn't possible. For example, to specify an element as `missing` with `v[end] = missing` will error, as missing can't be promoted to an integer.
|
||||
|
||||
If more than one value is referenced in the assignment, then more than one value can be specified on the right-hand side.
|
||||
|
||||
Mutation is different from reassignment. A command like `v=[1,2,3,0]` would have had the same effect as `v[end] = 0`, but would be quite different. The first *replaces* the binding to `v` with a new container, the latter reaches into the container and replaces just a value it holds.
|
||||
|
||||
### Size and type
|
||||
|
||||
The `length` of a container is the number of elements in linear order:
|
||||
|
||||
```{julia}
|
||||
length(v), length(t), length(m)
|
||||
```
|
||||
|
||||
The `isempty` method will indicate if the length is 0, perhaps in a performant way:
|
||||
|
||||
```{julia}
|
||||
isempty(v), isempty([]), isempty(t), isempty(())
|
||||
```
|
||||
|
||||
|
||||
The `size` of a container, when defined, takes into account its shape or the dimensions:
|
||||
|
||||
```{julia}
|
||||
size(v), size(m) # no size defined for tuples
|
||||
```
|
||||
|
||||
Arrays, and hence vectors and matrices have an element type given by `eltype` (the `typeof` method returns the container type:
|
||||
|
||||
```{julia}
|
||||
eltype(v), eltype(t), eltype(m)
|
||||
```
|
||||
|
||||
(The element type of the tuple is `Int64`, but this is only because of this particular tuple. Tuples are typically heterogeneous containers--not homogeneous like vectors--and do not expect to have a common type. The `NTuple` type is for tuples with elements of the same type.)
|
||||
|
||||
### Modifying the length of a container
|
||||
|
||||
Vectors and some other containers allow elements to be added on or elements to be taken off. In computer science a queue is a collection that is ordered and has addition at one or the other end. Vectors can be used as a queue, though for just that task, there are more performant structures available.
|
||||
|
||||
Two key methods for queues are `push!` and `pop!`. We `push!` elements onto the end of the queue:
|
||||
|
||||
```{julia}
|
||||
push!(v, 5)
|
||||
```
|
||||
|
||||
The output is expected -- `5` was added to the end of `v`. What might not be expected is the underlying `v` is changed without assignment. (Actually `mutated`, the underlying container assigned to the symbol `v` is extended, not replaced.)
|
||||
|
||||
:::{.callout-note}
|
||||
## Trailing exclamation point convention
|
||||
The function `push!` has a trailing exclamation point which is a `Julia` convention to indicate one of the underlying arguments (traditionally the first) will be *mutated* by the function call.
|
||||
:::
|
||||
|
||||
The `pop!` function is somewhat of a reverse: it takes the last element and "pops" it off the queue, leaving the queue one element shorter and returning the last element.
|
||||
|
||||
```{julia}
|
||||
pop!(v)
|
||||
```
|
||||
|
||||
```{julia}
|
||||
v
|
||||
```
|
||||
|
||||
There are also `pushfirst!`, `popfirst!`, `insert!` and `deleteat!` methods.
|
||||
|
||||
|
||||
### Iteration
|
||||
|
||||
A very fundamental operation is to iterate over the elements of a collection one by one.
|
||||
|
||||
In computer science the `for` loop is the basic construct to iterate over values. This example will iterate over `v` and add each value to `tot` which is initialized to be `0`:
|
||||
|
||||
```{julia}
|
||||
tot = 0
|
||||
for e in v
|
||||
tot = tot + e
|
||||
end
|
||||
tot
|
||||
```
|
||||
|
||||
The `for` loop construct is central in many programming languages; in `Julia` for loops are very performant and very flexible, however, they are more verbose than needed. (In the above example we had to initialize an accumulator and then write three lines for the loop, whereas `sum(v)` would do the same--and in this case more flexibly, with just a single call.) Alternatives are usually leveraged--we mention a few.
|
||||
|
||||
Iterating over a vector can be done by *value*, as above, or by *index*. For the latter the `eachindex` method creates an iterable for the indices of the container. For rectangular objects, like matrices, there are also many uses for `eachrow` and `eachcol`, though not in these notes.
|
||||
|
||||
|
||||
There are a few basic patterns where alternatives to a `for` loop exist. We discuss two:
|
||||
|
||||
* mapping a function or expression over each element in the collection
|
||||
* a reduction where a larger dimensional object is summarized by a lower dimensional one. In the example above, the $1$-dimensional vector is reduced to a $0$-dimensional scalar by summing the elements.
|
||||
|
||||
#### Comprehensions
|
||||
|
||||
In mathematics, set notation is often used to describe elements in a set.
|
||||
|
||||
For example, the first $5$ cubed numbers can be described by:
|
||||
|
||||
|
||||
$$
|
||||
\{x^3: x \text{ in } 1, 2,\dots, 5\}
|
||||
$$
|
||||
|
||||
Comprehension notation is similar. The above could be created in `Julia` with:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs = [1, 2, 3, 4, 5]
|
||||
[x^3 for x in xs]
|
||||
```
|
||||
|
||||
Comprehensions are one way of iterating over a collection and evaluating an expression on each element.
|
||||
|
||||
In the above, the value `x` takes on each value in `xs`. The variables may be tuples, as well.
|
||||
|
||||
The `enumerate` method wraps a container (or iterable) and iterates both the index and the value. This is useful, say for polynomials:
|
||||
|
||||
```{julia}
|
||||
x = 3
|
||||
as = [1, 2, 3] # evaluate a₀⋅x⁰, a₁⋅x¹, a₂⋅x²
|
||||
[a*x^(i-1) for (i, a) in enumerate(as)]
|
||||
```
|
||||
|
||||
(These values can then be easily summed to evaluate the polynomial.)
|
||||
|
||||
When iterating over `enumerate` a tuple is returned. The use of `(i, a)` to iterate over these tuples destructures the tuple into parts to be used in the expression.
|
||||
|
||||
The `zip` function also is useful to *pair* off iterators. Redoing the above to have the powers iterated over:
|
||||
|
||||
```{julia}
|
||||
as = [1, 2, 3]
|
||||
inds = [0, 1, 2]
|
||||
[a*x^i for (i, a) in zip(inds, as)]
|
||||
```
|
||||
|
||||
Like `enumerate`, the `zip` iterator has elements which are tuples.
|
||||
|
||||
|
||||
:::{.callout-note}
|
||||
## Note
|
||||
The style generally employed herein is to use plural variable names for a collection of values, such as the vector of $y$ values and singular names when a single value is being referred to, leading to expressions like "`x in xs`".
|
||||
|
||||
:::
|
||||
|
||||
|
||||
|
||||
#### Broadcasting a function call
|
||||
|
||||
If we have a vector, `xs`, and a function, `f`, to apply to each value, there is a simple means to achieve this task that is shorter than a `for` loop or the comprehension `[f(x) for x in s]`. By adding a "dot" between the function name and the parenthesis that enclose the arguments, instructs `Julia` to "broadcast" the function call. The details allow for more much flexibility, but, for this purpose, broadcasting will take each value in `xs` and apply `f` to it, returning a vector of the same size as `xs`. When more than one argument is involved, broadcasting will try to pad out different sized objects to the same shape. Broadcasting can also *fuse* combined function calls.
|
||||
|
||||
|
||||
For example, the following will find, using `sqrt`, the square root of each value in a vector:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs = [1, 1, 3, 4, 7]
|
||||
sqrt.(xs)
|
||||
```
|
||||
|
||||
This call finds the sine of each number in `xs`:
|
||||
|
||||
|
||||
```{julia}
|
||||
sin.(xs)
|
||||
```
|
||||
|
||||
For each function call, the `.(` (and not `(`) after the name is the surface syntax for broadcasting.
|
||||
|
||||
|
||||
The `^` operator is an *infix* operator. Infix operators can be broadcast, as well, by using the form `.` prior to the operator, as in:
|
||||
|
||||
|
||||
```{julia}
|
||||
xs .^ 2
|
||||
```
|
||||
|
||||
Here is an example involving the logarithm of a set of numbers. In astronomy, a logarithm with base $100^{1/5}$ is used for star [brightness](http://tinyurl.com/ycp7k8ay). We can use broadcasting to find this value for several values at once through:
|
||||
|
||||
|
||||
```{julia}
|
||||
ys = [1/5000, 1/500, 1/50, 1/5, 5, 50]
|
||||
base = (100)^(1/5)
|
||||
log.(base, ys)
|
||||
```
|
||||
|
||||
Broadcasting with multiple arguments allows for mixing of vectors and scalar values, as above, making it convenient when parameters are used. In broadcasting, there are times where it is desirable to treat a container as a scalar-like argument, a common idiom is to wrap that container in a 1-element tuple.
|
||||
|
||||
|
||||
As a final example, the task from statistics of centering and then squaring can be done with broadcasting. We go a bit further, showing how to compute the [sample variance](http://tinyurl.com/p6wa4r8) of a data set. This has the formula
|
||||
|
||||
|
||||
$$
|
||||
\frac{1}{n-1}\cdot ((x_1-\bar{x})^2 + \cdots + (x_n - \bar{x})^2).
|
||||
$$
|
||||
|
||||
This can be computed, with broadcasting, through:
|
||||
|
||||
|
||||
```{julia}
|
||||
#| hold: true
|
||||
import Statistics: mean
|
||||
xs = [1, 1, 2, 3, 5, 8, 13]
|
||||
n = length(xs)
|
||||
(1/(n-1)) * sum(abs2.(xs .- mean(xs)))
|
||||
```
|
||||
|
||||
This shows many of the manipulations that can be made with vectors. Rather than write `.^2`, we follow the definition of `var` and chose the possibly more performant `abs2` function which, in general, efficiently finds $|x|^2$ for various number types. The `.-` uses broadcasting to subtract a scalar (`mean(xs)`) from a vector (`xs`). Without the `.`, this would error.
|
||||
|
||||
Broadcasting is a widely used and powerful surface syntax which we will employ occasionally in the sequel.
|
||||
|
||||
|
||||
#### Mapping a function over a collection
|
||||
|
||||
The `map` function is very much related to broadcasting. Similarly named functions are found in many different programming languages. (The "dot" broadcast is mostly limited to `Julia` and mirrors a similar usage of a dot in `MATLAB`.) For those familiar with other programming languages, using `map` may seem more natural. Its syntax is `map(f, xs)`. There may be one or more iterable passed to `map`.
|
||||
|
||||
|
||||
For example, this will map `sin` over each value in `xs`, computing the same things as `sin.(xs)`:
|
||||
|
||||
```{julia}
|
||||
map(sin, xs)
|
||||
```
|
||||
|
||||
The `map` function can be used with one or more iterators.
|
||||
|
||||
The `map` function can also be used in combination with `reduce`, a reduction. Reductions take a container with one or more dimensions and reduces the number of dimensions. A example might be:
|
||||
|
||||
```{julia}
|
||||
sum(map(sin, xs))
|
||||
```
|
||||
|
||||
This has a performance drawback--there are two passes through the container, one to apply `sin` another to add.
|
||||
|
||||
The `mapreduce` function combines the map and reduce operations in one pass. It takes a third argument to reduce by in the second position. This is a *binary* operator. So this combination will map `sin` over `xs` and then add the results up:
|
||||
|
||||
```{julia}
|
||||
mapreduce(sin, +, xs)
|
||||
```
|
||||
|
||||
There are other specialized reduction functions that reverse the order of the mapper and the reducer. For example, we have `sum` (used above) and `prod` for adding and multiplying values in a collection:
|
||||
|
||||
```{julia}
|
||||
sum(xs), prod(xs)
|
||||
```
|
||||
|
||||
These are reductions, which which fall back to a `mapreduce` call. They require a starting value (`init`) of `0` and `1` (which in this case can be determined from `xs`). The `sum` and `prod` function also allow as a first argument an initial function to map over the collection:
|
||||
|
||||
```{julia}
|
||||
sum(sin, xs)
|
||||
```
|
||||
|
||||
|
||||
#### Other reductions
|
||||
|
||||
There are other reductions, which summarize a container. We mention those related to the maximum or minimum of a collection. For these examples, we have
|
||||
|
||||
```{julia}
|
||||
v = [1, 2, 3, 4]
|
||||
```
|
||||
|
||||
The largest value in a numeric collection is returned by `maximum`:
|
||||
|
||||
```{julia}
|
||||
maximum(v)
|
||||
```
|
||||
|
||||
Where this maximum occurred is returned by `argmax`:
|
||||
|
||||
```{julia}
|
||||
argmax(v)
|
||||
```
|
||||
|
||||
For `v` these are the same. But if we were to apply `sin` to `v` say, then the result may not be in order. This can be done with, say, a call to `map` and then `maximum`, but the functions allow an initial function to be specified:
|
||||
|
||||
```{julia}
|
||||
maximum(sin, v), argmax(sin, v)
|
||||
```
|
||||
|
||||
This combination is also the duty of `findmax`:
|
||||
|
||||
```{julia}
|
||||
findmax(sin, v)
|
||||
```
|
||||
|
||||
There are also `minimum`, `argmin`, and `findmin`.
|
||||
|
||||
The `extrema` function returns the maximum and minimum of the collection:
|
||||
|
||||
```{julia}
|
||||
extrema(v)
|
||||
```
|
||||
|
||||
:::{.callout-note}
|
||||
## `maximum` and `max`
|
||||
In `Julia` there are two related functions: `maximum` and `max`. The `maximum` function generically returns the largest element in a collection. The `max` function returns the maximum of its *arguments*.
|
||||
|
||||
That is, these return identical values:
|
||||
|
||||
```{julia}
|
||||
xs = [1, 3, 2]
|
||||
maximum(xs), max(1, 3, 2), max(xs...)
|
||||
```
|
||||
|
||||
The latter using *splatting* to iterate over each value in `xs` and pass it to `max` as an argument.
|
||||
:::
|
||||
|
||||
### Predicate functions
|
||||
|
||||
A few reductions work with *predicate* functions--those that return `true` or `false`. Let's use `iseven` as an example, which tests if a number is even.
|
||||
|
||||
We can check if *all* the alements of a container are even or if *any* of the elements of a container are even with `all` and `even`:
|
||||
|
||||
```{julia}
|
||||
xs = [1, 1, 2, 3, 5]
|
||||
all(iseven, xs), any(iseven, xs)
|
||||
```
|
||||
|
||||
|
||||
Related, we can count the number of `true` responses of the predicate function:
|
||||
|
||||
```{julia}
|
||||
count(iseven, xs)
|
||||
```
|
||||
|
||||
|
||||
#### methods for associative arrays
|
||||
|
||||
For dictionaries, the collection is unordered (by default), but iteration can still be done over "key-value" pairs.
|
||||
|
||||
In `Julia` a `Pair` matches a key and a value into one entity. Pairs are made with the `=>` notation with the `key` on the left and the value on the right.
|
||||
|
||||
|
||||
Dictionaries are a collection of pairs. The `Dict` constructor can be passed pairs directly:
|
||||
|
||||
```{julia}
|
||||
ascii = Dict("a"=>97, "b"=>98, "c"=>99) # etc.
|
||||
```
|
||||
|
||||
To iterate over these, the `pairs` iterator is useful:
|
||||
|
||||
```{julia}
|
||||
collect(pairs(ascii))
|
||||
```
|
||||
|
||||
(We used `collect` to iterate over values and return them as a vector.)
|
||||
|
||||
The keys are returned by `keys`, the values by `values`:
|
||||
|
||||
```{julia}
|
||||
keys(ascii)
|
||||
```
|
||||
|
||||
|
||||
|
||||
@@ -993,6 +1117,7 @@ From [transum.org](http://www.transum.org/Maths/Exam/Online_Exercise.asp?Topic=V
|
||||
#| hold: true
|
||||
#| echo: false
|
||||
let
|
||||
gr()
|
||||
p = plot(xlim=(0,10), ylim=(0,5), legend=false, framestyle=:none)
|
||||
for j in (-3):10
|
||||
plot!(p, [j, j + 5], [0, 5*sqrt(3)], color=:blue, alpha=0.5)
|
||||
@@ -1058,6 +1183,12 @@ answ = 4
|
||||
radioq(choices, answ)
|
||||
```
|
||||
|
||||
```{julia}
|
||||
#| echo: false
|
||||
plotly()
|
||||
nothing
|
||||
```
|
||||
|
||||
###### Question
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user