-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add an example (comparing with Julia)
- Loading branch information
Showing
2 changed files
with
57 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(()) | ||
} |