pub struct Bisection<F> { /* private fields */ }
Expand description
Simple bisection method.
See https://en.wikipedia.org/wiki/Bisection_method for details on the algorithm.
The x
returned is an array [f64;2]
which bounds the root.
The midpoint of the range is the best estimate of the root, and x_mid and
f_mid (the function evalution at the midpoint) are also available on the algo
§Examples
from https://en.wikipedia.org/wiki/Bisection_method#Example:_Finding_the_root_of_a_polynomial
use stepwise::{Driver as _, fixed_iters, algos::Bisection, assert_approx_eq};
let f = |x: f64| x.powi(3) - x - 2.0;
let algo = Bisection::from_fn(f, [1.0, 2.0]).expect("range didn't bound the solution");
let mut driver = fixed_iters(algo, 15);
println!("iter x0 x1 x-mid f");
let (solved, step) = driver
.on_step(|algo, step| {
let [x0, x1] = algo.x();
println!(
"{i:>4} [{x0:.7}, {x1:.7}] {xmid:.7} {f:+.7}",
i = step.iteration(),
xmid = (x0 + x1) / 2.0,
f = algo.f_mid()
);
})
.solve()
.unwrap();
assert_approx_eq!(solved.x().as_slice(), &[1.5213, 1.5213], 0.0001);
Implementations§
Source§impl Bisection<()>
impl Bisection<()>
Sourcepub fn from_falliable_fn<F, E>(
f: F,
[lo, hi]: [f64; 2],
) -> Result<Bisection<F>, DriverError>
pub fn from_falliable_fn<F, E>( f: F, [lo, hi]: [f64; 2], ) -> Result<Bisection<F>, DriverError>
Create a new bisection algo from an falliable function f: f64 -> Result<f64,E>
§Errors
DriverError::AlgoError
if the calls to the function f fail.DriverError::InitialCondition
if [lo,hi] doesn’t bound the root.
Trait Implementations§
Source§impl<E, F> Algo for Bisection<F>
impl<E, F> Algo for Bisection<F>
type Error = E
fn step(&mut self) -> (ControlFlow<()>, Result<(), E>)
Source§fn read_file(&mut self, fmt: &FileFormat, r: &mut dyn Read) -> Result<(), Error>
fn read_file(&mut self, fmt: &FileFormat, r: &mut dyn Read) -> Result<(), Error>
Implement this method to support recovery from a checkpoint file Read more
Source§fn write_file(&self, fmt: &FileFormat, w: &mut dyn Write) -> Result<(), Error>
fn write_file(&self, fmt: &FileFormat, w: &mut dyn Write) -> Result<(), Error>
Implement this trait to support writing checkpoint files Read more
impl<F> StructuralPartialEq for Bisection<F>
Auto Trait Implementations§
impl<F> Freeze for Bisection<F>where
F: Freeze,
impl<F> RefUnwindSafe for Bisection<F>where
F: RefUnwindSafe,
impl<F> Send for Bisection<F>where
F: Send,
impl<F> Sync for Bisection<F>where
F: Sync,
impl<F> Unpin for Bisection<F>where
F: Unpin,
impl<F> UnwindSafe for Bisection<F>where
F: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more