Skip to content

Instantly share code, notes, and snippets.

@robertDurst
Created July 20, 2018 15:24
Show Gist options
  • Save robertDurst/24d286725b70b54b90918238be495451 to your computer and use it in GitHub Desktop.
Save robertDurst/24d286725b70b54b90918238be495451 to your computer and use it in GitHub Desktop.
LaGrange interpolation implementation in rust demonstrating how to calculate f(0) for a given set of points.
// Because of this feature gate, you must use a nightly
// version of rust.
#![feature(euclidean_division)]
#[derive(Debug)]
struct Point {
x: f64,
y: f64,
}
fn interpolate(f: Vec<Point>, p: f64) -> f64 {
// Since we will loop over all the points in the vector, capture n.
// Also, convert n to usize because we will be using th iterator
// associated types as indices.
let n = f.len() as usize;
let mut result = 0.0;
// Each point in the vector of "known" points will be interpolated
// to calculate the point at f(0).
for i in 0..n {
let mut term = f[i].y;
// A good old nested for loop :)
for j in 0..n {
if i != j {
// X's should be unique
assert!(f[i].x - f[j].x != 0.0);
let denominator = f[i].x - f[j].x;
let numerator = - f[j].x;
term = term * (numerator/denominator);
}
}
result += term;
result = result.mod_euc(p)
}
result
}
fn main() {
let f = vec![
Point{ x: 4.0, y: 1.0},
Point{ x: 3.0, y: 2.0},
Point{ x: 5.0, y: 2.0},
];
let p = 11.0;
let result = interpolate(f, p);
println!("f(0) = {}", result);
}
// Output:
// f(0) = 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment