# Applications with scalar functions


{{< include ../_common_code.qmd >}}

This section uses these add-on packages:


```{julia}
using CalculusWithJulia
using Plots
plotly()
using SymPy
using Roots
```

##### Example


Consider the function $f(x,y) = x^2 + 3y^2 -x$ over the region $x^2 + y^2 \leq 1$. This is a continuous function over a closed set, so will have both an absolute maximum and minimum. Find these from an investigation of the critical points and the boundary points.


The gradient is easily found: $\nabla{f} = \langle 2x - 1, 6y \rangle$, and is $\vec{0}$ only at $\vec{a} = \langle 1/2, 0 \rangle$. The Hessian is:


$$
H =
\begin{bmatrix}
2 & 0\\
0 & 6
\end{bmatrix}.
$$

At $\vec{a}$ this has positive determinant and $f_{xx} > 0$, so $\vec{a}$ corresponds to a *local* minimum with values $f(\vec{a}) = (1/2)^2 + 3(0) - 1/2 = -1/4$. The absolute maximum and minimum may occur here (well, not the maximum) or on the boundary, so that must be considered. In this case we can easily parameterize the boundary and turn this into the univariate case:


```{julia}
fₗ(x,y) = x^2 + 2y^2 - x
gammaₗ(t) = [cos(t), sin(t)]  # traces out x^2 + y^2 = 1 over [0, 2pi]
gₗ = splat(fₗ) ∘ gammaₗ

cpsₗ = find_zeros(gₗ', 0, 2pi) # critical points of g
append!(cpsₗ, [0, 2pi])
unique!(cpsₗ)
gₗ.(cpsₗ)
```

We see that maximum value is `2.25` and that the interior point, $\vec{a}$, will be where the minimum value occurs. To see exactly where the maximum occurs, we look at the values of gamma:

```{julia}
inds = [2,4]
cpsₗ[inds]
```

These are multiples of $\pi$:


```{julia}
cpsₗ[inds]/pi
```

So we have the maximum occurs at the angles $2\pi/3$ and $4\pi/3$. Here we visualize, using a hacky trick of assigning `NaN` values to the function to avoid plotting outside the circle:


```{julia}
hₗ(x,y) = fₗ(x,y) * (x^2 + y^2 <= 1 ? 1 : NaN)
```

```{julia}
gr()
```

```{julia}
#| hold: true
xs = ys = range(-1,1, length=100)
plt = surface(xs, ys, hₗ)

ts = cpsₗ  # 2pi/3 and 4pi/3 by above
xs, ys = cos.(ts), sin.(ts)
zs = fₗ.(xs, ys)
scatter3d!(xs, ys, zs)
#tuple.(xs, ys, zs)
#plot!(plt, tuple.(xs, ys, zs); linetype=:scatter)
#plt
```

A contour plot also shows that some---and only one---extrema happens on the interior:

<!--

```{julia}
#| hold: true
xs = ys = range(-1,1, length=100)
contour(xs, ys, hₗ)
```

The extrema are identified by the enclosing regions, in this case the one around the point $(1/2, 0)$.
-->
