Skip to content

Instantly share code, notes, and snippets.

@hickford
Created February 12, 2019 16:23
Show Gist options
  • Save hickford/20d60cfc39e187b140ade532761faae5 to your computer and use it in GitHub Desktop.
Save hickford/20d60cfc39e187b140ade532761faae5 to your computer and use it in GitHub Desktop.
/// Assuming f is a continuous function with a single minimum and no maximums in (lower,upper), find the minimum point.
let rec minimise f lower upper =
let lmid = (2.0*lower+upper)/3.0
let umid = (lower+2.0*upper)/3.0
if lmid = lower && umid = upper then
Seq.minBy f [lower; upper]
else if f lmid < f umid then
minimise f lower umid
else
minimise f lmid upper
let solution = minimise Math.Cos 0.0 6.0
printf "solution: %g" solution
printf "absolute error: %g" (solution - Math.PI)
/// Binary search to find root.
let rec root f lower upper =
let mid = (lower+upper)/2.0
if lower = mid || mid = upper then
Seq.minBy (f >> abs) [lower; mid; upper]
else if f lower * f mid <= 0.0 then
root f lower mid
else
root f mid upper
let solution2 = root Math.Sin 3.0 4.0
printf "solution: %g" solution2
printf "absolute error: %g" (solution2 - Math.PI)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment