diff --git a/examples/x_sinx_levels.jl b/examples/x_sinx_levels.jl new file mode 100644 index 0000000..436b711 --- /dev/null +++ b/examples/x_sinx_levels.jl @@ -0,0 +1,25 @@ +using Pkg +Pkg.add("NonlinearSolve") +using NonlinearSolve + +N = 100_000 +levels = 1.5 * rand(N) +out = zeros(N) + +f(x, lv) = x * sin(x) - lv + +function f(out, levels, u0) + for i in 1:N + out[i] = solve(NonlinearProblem{false}( + NonlinearFunction{false}(f), u0, levels[i]), + NewtonRaphson()).u + end +end + +@time f(out, levels, 1.0) + +# Julia 1.9.4 (Intel Core i7-7500U CPU @ 2.70GHz) +# 0.133063 seconds (1.30 M allocations: 141.891 MiB, 14.63% gc time) +# +# Note that, on the first run, the following was reported: +# 299.023886 seconds (777.52 M allocations: 164.623 GiB, 1.72% gc time, 99.94% compilation time) diff --git a/examples/x_sinx_levels.rs b/examples/x_sinx_levels.rs new file mode 100644 index 0000000..b8b4a0b --- /dev/null +++ b/examples/x_sinx_levels.rs @@ -0,0 +1,32 @@ +//! Compute level sets of x sin(x) +//! See https://twitter.com/walkingrandomly/status/1544615360833507329 +//! https://twitter.com/ChrisRackauckas/status/1544743542094020615 +//! and [Matlab R2023a][]. +//! +//! [Matlab R2023a]: https://blogs.mathworks.com/matlab/2023/05/15/from-hpc-consultancy-to-a-faster-fzero-function-in-matlab-r2023a/ + +use std::{error::Error, iter, time::Instant}; +use root1d::{toms748, bisect}; +use rand::prelude::*; + +fn main() -> Result<(), Box> { + const N: usize = 100_000; + let levels: Vec<_> = iter::from_fn(|| Some(1.5 * random::())) + .take(N).collect(); + let mut out = Vec::with_capacity(N); + + let now = Instant::now(); + for lv in &levels { + out.push(bisect(|x: f64| x * x.sin() - lv, 0., 2.).root()?); + } + println!("bisect: {} secs", now.elapsed().as_secs_f64()); + + out.clear(); + let now = Instant::now(); + for lv in &levels { + out.push(toms748(|x: f64| x * x.sin() - lv, 0., 2.).root()?); + } + println!("toms748: {} secs", now.elapsed().as_secs_f64()); + + Ok(()) +}