Skip to content

Commit caa1509

Browse files
added Langrange Polynomial Interpolation by Timothy Kandiado
1 parent 3007179 commit caa1509

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/math/interpolation.rs

+57
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,33 @@ pub fn linear_interpolation(x: f64, point0: (f64, f64), point1: (f64, f64)) -> f
77
point0.1 + (x - point0.0) * (point1.1 - point0.1) / (point1.0 - point0.0)
88
}
99

10+
pub fn langrange_polynomial_interpolation(x: f64, defined_points: &Vec<(f64, f64)>) -> f64 {
11+
let mut defined_x_values: Vec<f64> = Vec::new();
12+
let mut defined_y_values: Vec<f64> = Vec::new();
13+
14+
for (x, y) in defined_points {
15+
defined_x_values.push(*x);
16+
defined_y_values.push(*y);
17+
}
18+
19+
let mut sum = 0.0;
20+
21+
for y_index in 0..defined_y_values.len() {
22+
let mut numerator = 1.0;
23+
let mut denominator = 1.0;
24+
for x_index in 0..defined_x_values.len() {
25+
if y_index == x_index {
26+
continue;
27+
}
28+
denominator *= defined_x_values[y_index] - defined_x_values[x_index];
29+
numerator *= x - defined_x_values[x_index];
30+
}
31+
32+
sum += numerator / denominator * defined_y_values[y_index];
33+
}
34+
sum
35+
}
36+
1037
#[cfg(test)]
1138
mod tests {
1239

@@ -32,4 +59,34 @@ mod tests {
3259
linear_interpolation(x1, point2, point1)
3360
);
3461
}
62+
63+
#[test]
64+
fn test_langrange_polynomial_interpolation() {
65+
// defined values for x^2 function
66+
let defined_points = vec![(0.0, 0.0), (1.0, 1.0), (2.0, 4.0), (3.0, 9.0)];
67+
68+
// check for equality
69+
assert_eq!(
70+
langrange_polynomial_interpolation(1.0, &defined_points),
71+
1.0
72+
);
73+
assert_eq!(
74+
langrange_polynomial_interpolation(2.0, &defined_points),
75+
4.0
76+
);
77+
assert_eq!(
78+
langrange_polynomial_interpolation(3.0, &defined_points),
79+
9.0
80+
);
81+
82+
//other
83+
assert_eq!(
84+
langrange_polynomial_interpolation(0.5, &defined_points),
85+
0.25
86+
);
87+
assert_eq!(
88+
langrange_polynomial_interpolation(2.5, &defined_points),
89+
6.25
90+
);
91+
}
3592
}

src/math/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ pub use self::greatest_common_divisor::{
6868
greatest_common_divisor_stein,
6969
};
7070
pub use self::interest::{compound_interest, simple_interest};
71-
pub use self::interpolation::linear_interpolation;
71+
pub use self::interpolation::{langrange_polynomial_interpolation, linear_interpolation};
7272
pub use self::karatsuba_multiplication::multiply;
7373
pub use self::lcm_of_n_numbers::lcm;
7474
pub use self::linear_sieve::LinearSieve;

0 commit comments

Comments
 (0)