Skip to content

Instantly share code, notes, and snippets.

Created March 9, 2018 21:24
Show Gist options
  • Save anonymous/45827793ffdfffa354755c1bb25237bb to your computer and use it in GitHub Desktop.
Save anonymous/45827793ffdfffa354755c1bb25237bb to your computer and use it in GitHub Desktop.
Rust code shared from the playground
extern crate rayon;
use rayon::iter::IntoParallelIterator;
use rayon::iter::ParallelIterator;
fn main() {
let val = integral(|x| x * x, -1f64, 1f64);
println!("{}", val);
}
fn integral<F>(fun: F, min: f64, max: f64) -> f64
where
F: Fn(f64) -> f64 + Sized + Sync,
{
let steps: usize = 100_000;
let step_size: f64 = (max - min) / (steps as f64);
(0..steps)
.into_par_iter()
.fold(
|| 0f64,
|acc, x| {
let i: f64 = x as f64;
let left_input = min + (i * step_size);
let right_input = left_input + step_size;
let left_output = fun(left_input);
let right_output = fun(right_input);
let midpt = (left_output + right_output) / 2f64;
acc + (midpt * step_size)
},
)
.reduce(|| 0f64, |acc, a| acc + a)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment