Horner's rule for polynomial evaluation: Difference between revisions

Content added Content deleted
(Horner's rule for polynomial evaluation en FreeBASIC)
(→‎{{header|Rust}}: Zero trait deprecated, moved into num crate. Compiles in stable (1.37).)
Line 1,762: Line 1,762:
}</lang>
}</lang>


A generic version that works with any number type and much more. So much more, it's hard to imagine what that may be useful for. <br>
A generic version that works with any number type and much more. So much more, it's hard to imagine what that may be useful for.
<lang rust>extern crate num; // 0.2.0
'''Uses a gated feature (the Zero trait), only works in unstable Rust'''
use num::Zero;
<lang rust>#![feature(zero_one)
use std::num::Zero;
use std::ops::{Add, Mul};
use std::ops::{Mul, Add};


fn horner<Arr,Arg, Out>(v: &[Arr], x: Arg) -> Out
fn horner<Arr, Arg, Out>(v: &[Arr], x: Arg) -> Out
where Arr: Clone,
where
Arg: Clone,
Arr: Clone,
Arg: Clone,
Out: Zero + Mul<Arg, Output=Out> + Add<Arr, Output=Out>,
Out: Zero + Mul<Arg, Output = Out> + Add<Arr, Output = Out>,
{
{
v.iter()
v.iter().rev().fold(Zero::zero(), |acc, coeff| acc*x.clone() + coeff.clone())
.rev()
.fold(Zero::zero(), |acc, coeff| acc * x.clone() + coeff.clone())
}
}


fn main() {
fn main() {
let v = [-19., 7., -4., 6.];
let v = [-19., 7., -4., 6.];
let output: f64 = horner(&v, 3.0);
let output: f64 = horner(&v, 3.0);
println!("result: {}", output);
println!("result: {}", output);
}</lang>
}</lang>