Skip to content

Commit

Permalink
Add an example (comparing with Julia)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chris00 committed Dec 27, 2023
1 parent 8604970 commit de26e0a
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ nightly = []
[dev-dependencies]
criterion = "0.3.5"
roots = "0.0.7"
rand = "0.8.5"

[[example]]
name = "basic"
Expand Down
25 changes: 25 additions & 0 deletions examples/x_sinx_levels.jl
Original file line number Diff line number Diff line change
@@ -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)
32 changes: 32 additions & 0 deletions examples/x_sinx_levels.rs
Original file line number Diff line number Diff line change
@@ -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<dyn Error + 'static>> {
const N: usize = 100_000;
let levels: Vec<_> = iter::from_fn(|| Some(1.5 * random::<f64>()))
.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(())
}

0 comments on commit de26e0a

Please sign in to comment.