Roots of a function: Difference between revisions

(added Rust programming solution)
Line 2,820:
<pre>
Result : Three([0.000000059604645, 0.99999994, 2.0])
</pre>
 
Another without external crates:
<lang rust>
use num::Float;
 
/// Note: We cannot use `range_step` here because Floats don't implement
/// the `CheckedAdd` trait.
fn find_roots<T, F>(f: F, start: T, stop: T, step: T, epsilon: T) -> Vec<T>
where
T: Copy + PartialOrd + Float,
F: Fn(T) -> T,
{
let mut ret = vec![];
let mut current = start;
while current < stop {
if f(current).abs() < epsilon {
ret.push(current);
}
current = current + step;
}
ret
}
 
fn main() {
let roots = find_roots(
|x: f64| x * x * x - 3.0 * x * x + 2.0 * x,
-1.0,
3.0,
0.0001,
0.00000001,
);
 
println!("roots of f(x) = x^3 - 3x^2 + 2x are: {:?}", roots);
}
 
</lang>
{{out}}
<pre>
roots of f(x) = x^3 - 3x^2 + 2x are: [-0.00000000000009381755897326649, 0.9999999999998124, 1.9999999999997022]
</pre>
 
Anonymous user