Last time¶
Conditioning of a problem versus elementary steps
Forward and backward error
Forward and backward stability
Computing volume of a polygon
Demos and discussion
Today¶
Rootfinding as a modeling tool
Use Roots.jl to solve
Introduce Bisection
Convergence classes
Updates¶
Drop-in hours¶
Jed
Tuesday, 2-3pm in ECOT 824
Zach
Tuesday, 11:45-12:45 in ECOT 831
Thursday, 1:00-2:00 and 2:45-3:45 in ECOT 832
Activity: 01-Taylor-Series¶
Portfolio and journaling¶
using Plots
default(linewidth=4)Rootfinding¶
Given , find such that .
We’ll work with scalars ( and are just numbers) for now, and revisit later when they vector-valued.
Change inputs to outputs¶
We aren’t given , but rather an algorithm f(x) that approximates it.
Sometimes we get extra information, like
fp(x)that approximatesIf we have source code for
f(x), maybe it can be transformed “automatically”
Nesting matryoshka dolls of rootfinding¶
I have a function (pressure, temperature) (density, energy)
I need (density, energy) (pressure, temperature)
I know what condition is satisfied across waves, but not the state on each side.

Toro (2009)
Given a proposed state, I can measure how much (mass, momentum, energy) is not conserved.
Find the solution that conserves exactly
I can compute lift given speed and angle of attack
How much can the plane lift?
How much can it lift on a short runway?

Discuss: rootfinding and inverse problems¶
Inverse kinematics for robotics
(statics) how much does each joint an robotic arm need to move to grasp an object
(with momentum) fastest way to get there (motors and arms have finite strength)
similar for virtual reality
Infer a light source (or lenses/mirrors) from an iluminated scene
Imaging
radiologist seeing an x-ray is mentally inferring 3D geometry from 2D image
computed tomography (CT) reconstructs 3D model from multiple 2D x-ray images
seismology infers subsurface/deep earth structure from seismograpms
Example: Queueing¶
In a simple queueing model, there is an arrival rate and a departure (serving) rate. While waiting in the queue, there is a probability of “dropping out”. The length of the queue in this model is
One model for the waiting time (where these rates are taken from exponential distributions) is
wait(arrival, departure) = log(arrival / departure) / departure
plot(d -> wait(1, d), xlims=(.1, 1), xlabel="departure", ylabel="wait")Departure rate given wait¶
Easy to measure wait
I have a limited tolerance for waiting
my_wait = 0.8
plot([d -> wait(1, d) - my_wait, d -> 0], xlims=(.1, 1), xlabel="departure", ylabel="wait")#import Pkg; Pkg.add("Roots")
using Roots
d0 = find_zero(d -> wait(1, d) - my_wait, 1)
plot([d -> wait(1, d) - my_wait, d -> 0], xlims=(.1, 1), xlabel="departure", ylabel="wait")
scatter!([d0], [0], marker=:circle, color=:black, title="d0 = $d0")ArgumentError: Package Roots not found in current path.
- Run `import Pkg; Pkg.add("Roots")` to install the Roots package.
Stacktrace:
[1] macro expansion
@ ./loading.jl:2470 [inlined]
[2] macro expansion
@ ./lock.jl:376 [inlined]
[3] __require(into::Module, mod::Symbol)
@ Base ./loading.jl:2453
[4] require(into::Module, mod::Symbol)
@ Base ./loading.jl:2429
[5] eval(m::Module, e::Any)
@ Core ./boot.jl:489Example: Nonlinear Elasticity¶
Strain-energy formulation¶
where and are invariants defined in terms of the principle stretches .
Uniaxial extension¶
In the experiment, we would like to know the stress as a function of the stretch . We don’t know , and will have to determine it by solving an equation.
How much does the volume change?¶
Using symmetries of uniaxial extension, we can write an equation that must be satisfied. We’ll need to solve a rootfinding problem to compute .
function f(lambda, J)
C_1 = 1.5e6
D_1 = 1e8
D_1 * J^(8/3) - D_1 * J^(5/3) + C_1 / (3*lambda) * J - C_1 * lambda^2/3
end
plot(J -> f(4, J), xlims=(0.1, 3), xlabel="J", ylabel="f(J)")find_J(lambda) = find_zero(J -> f(lambda, J), 1)
plot(find_J, xlims=(0.1, 5), xlabel="lambda", ylabel="J")UndefVarError: `find_zero` not defined in `Main`
Suggestion: check for spelling errors or missing imports.
Stacktrace:
[1] find_J(lambda::Float64)
@ Main ./In[7]:1
[2] call_composed (repeats 2 times)
@ ./operators.jl:1099 [inlined]
[3] (::ComposedFunction{ComposedFunction{RecipesPipeline.var"#scale_func##0#scale_func##1"{Symbol}, var"#find_J"}, RecipesPipeline.var"#inverse_scale_func##0#inverse_scale_func##1"{Symbol}})(x::Float64; kw::@Kwargs{})
@ Base ./operators.jl:1096
[4] ComposedFunction
@ ./operators.jl:1096 [inlined]
[5] (::PlotUtils.var"#27#28"{ComposedFunction{ComposedFunction{RecipesPipeline.var"#scale_func##0#scale_func##1"{Symbol}, var"#find_J"}, RecipesPipeline.var"#inverse_scale_func##0#inverse_scale_func##1"{Symbol}}})(x::Float64)
@ PlotUtils ~/.julia/packages/PlotUtils/HX80C/src/adapted_grid.jl:48
[6] _broadcast_getindex_evalf
@ ./broadcast.jl:699 [inlined]
[7] _broadcast_getindex
@ ./broadcast.jl:672 [inlined]
[8] _getindex
@ ./broadcast.jl:620 [inlined]
[9] getindex
@ ./broadcast.jl:616 [inlined]
[10] copy(bc::Base.Broadcast.Broadcasted{Base.Broadcast.DefaultArrayStyle{1}, Tuple{Base.OneTo{Int64}}, PlotUtils.var"#27#28"{ComposedFunction{ComposedFunction{RecipesPipeline.var"#scale_func##0#scale_func##1"{Symbol}, var"#find_J"}, RecipesPipeline.var"#inverse_scale_func##0#inverse_scale_func##1"{Symbol}}}, Tuple{Vector{Float64}}})
@ Base.Broadcast ./broadcast.jl:933
[11] materialize
@ ./broadcast.jl:894 [inlined]
[12] adapted_grid(f::Any, minmax::Tuple{Float64, Float64}; max_recursions::Int64, max_curvature::Float64, n_points::Int64)
@ PlotUtils ~/.julia/packages/PlotUtils/HX80C/src/adapted_grid.jl:59
[13] adapted_grid(f::Any, minmax::Tuple{Float64, Float64})
@ PlotUtils ~/.julia/packages/PlotUtils/HX80C/src/adapted_grid.jl:13
[14] _scaled_adapted_grid(f::Function, xscale::Symbol, yscale::Symbol, xmin::Float64, xmax::Int64)
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/user_recipe.jl:322
[15] macro expansion
@ ~/.julia/packages/RecipesPipeline/BGM3l/src/user_recipe.jl:265 [inlined]
[16] apply_recipe(plotattributes::AbstractDict{Symbol, Any}, f::Function, xmin::Number, xmax::Number)
@ RecipesPipeline ~/.julia/packages/RecipesBase/BRe07/src/RecipesBase.jl:300
[17] _process_userrecipes!(plt::Any, plotattributes::Any, args::Any)
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/user_recipe.jl:38
[18] recipe_pipeline!(plt::Any, plotattributes::Any, args::Any)
@ RecipesPipeline ~/.julia/packages/RecipesPipeline/BGM3l/src/RecipesPipeline.jl:72
[19] _plot!(plt::Plots.Plot, plotattributes::Any, args::Any)
@ Plots ~/.julia/packages/Plots/xC48f/src/plot.jl:223
[20] plot(args::Any; kw...)
@ Plots ~/.julia/packages/Plots/xC48f/src/plot.jl:102
[21] top-level scope
@ In[7]:2
[22] eval(m::Module, e::Any)
@ Core ./boot.jl:489WARNING: Detected access to binding `Main.find_J` in a world prior to its definition world.
Julia 1.12 has introduced more strict world age semantics for global bindings.
!!! This code may malfunction under Revise.
!!! This code will error in future versions of Julia.
Hint: Add an appropriate `invokelatest` around the access to this binding.
To make this warning an error, and hence obtain a stack trace, use `julia --depwarn=error`.
An algorithm: Bisection¶
Bisection is a rootfinding technique that starts with an interval containing a root and does not require derivatives. Suppose is continuous. What is a sufficient condition for to have a root on ?
hasroot(f, a, b) = f(a) * f(b) < 0
f(x) = cos(x) - x
plot(f)Bisection¶
function bisect(f, a, b, tol)
mid = (a + b) / 2
if abs(b - a) < tol
return mid
elseif hasroot(f, a, mid)
return bisect(f, a, mid, tol)
else
return bisect(f, mid, b, tol)
end
end
x0 = bisect(f, -1, 3, 1e-5)
x0, f(x0)(0.7390861511230469, -1.7035832658995886e-6)How fast does it converge?¶
function bisect_hist(f, a, b, tol)
mid = (a + b) / 2
if abs(b - a) < tol
return [mid]
elseif hasroot(f, a, mid)
return prepend!(bisect_hist(f, a, mid, tol), [mid])
else
return prepend!(bisect_hist(f, mid, b, tol), [mid])
end
endbisect_hist (generic function with 1 method)bisect_hist(f, -1, 3, 1e-4)17-element Vector{Float64}:
1.0
0.0
0.5
0.75
0.625
0.6875
0.71875
0.734375
0.7421875
0.73828125
0.740234375
0.7392578125
0.73876953125
0.739013671875
0.7391357421875
0.73907470703125
0.739105224609375Iterative bisection¶
Data structures often optimized for appending rather than prepending.
Bounds stack space
f(x) = cos(x) - x
hasroot(f, a, b) = f(a) * f(b) < 0
function bisect_iter(f, a, b, tol)
hist = Float64[]
while abs(b - a) > tol
mid = (a + b) / 2
push!(hist, mid)
if hasroot(f, a, mid)
b = mid
else
a = mid
end
end
hist
endbisect_iter (generic function with 1 method)length(bisect_iter(f, -1, 3, 1e-20))56hist = bisect_iter(f, -1, 3, 1e-10)
r = hist[end] # What are we trusting?
hist = hist[1:end-1]
scatter( abs.(hist .- r), yscale=:log10)
ks = 1:length(hist)
plot!(ks, 4 * (.5 .^ ks))Evidently the error after bisections satisfies the bound
Convergence classes¶
A convergent rootfinding algorithm produces a sequence of approximations such that
where . For analysis, it is convenient to define the errors . We say that an iterative algorithm is -linearly convergent if
(The is for “quotient”.) A smaller convergence factor represents faster convergence. A slightly weaker condition (-linear convergence or just linear convergence) is that
for all sufficiently large when the sequence converges -linearly to 0.
ρ = 0.8
errors = [1.]
for i in 1:30
next_e = errors[end] * ρ
push!(errors, next_e)
end
plot(errors, yscale=:log10, ylims=(1e-10, 1))e = hist .- r
scatter(abs.(errors[2:end] ./ errors[1:end-1]), ylims=(0,1))Bisection: A = q-linearly convergent, B = r-linearly convergent, C = neither¶
Remarks on bisection¶
Specifying an interval is often inconvenient
An interval in which the function changes sign guarantees convergence (robustness)
No derivative information is required
If bisection works for , then it works and gives the same accuracy for where .
Roots of even degree are problematic
A bound on the solution error is directly available
The convergence rate is modest -- one iteration per bit of accuracy
For you¶
Share an equation that is useful for one task, but requires rootfinding for another task.
OR: explain a system in which one stakeholder has the natural inputs, but a different stakeholder only knows outputs.
Please collaborate.