soilrust/
helper.rs

1/// Performs linear interpolation for a given x value based on provided x and y vectors.
2///
3/// # Arguments
4/// * `x_values` - Array of x-axis values (must be sorted)
5/// * `y_values` - Array of y-axis values
6/// * `x` - The x value for which to interpolate
7///
8/// # Returns
9/// * Interpolated y value as f64
10///
11/// # Panics
12/// If x_values and y_values lengths are not equal or x is out of range.
13pub fn interp1d(x_values: &[f64], y_values: &[f64], x: f64) -> f64 {
14    assert_eq!(
15        x_values.len(),
16        y_values.len(),
17        "x_values and y_values must have the same length"
18    );
19
20    if x <= x_values[0] {
21        return y_values[0];
22    }
23    if x >= x_values[x_values.len() - 1] {
24        return y_values[y_values.len() - 1];
25    }
26
27    for i in 0..x_values.len() - 1 {
28        let x0 = x_values[i];
29        let x1 = x_values[i + 1];
30        let y0 = y_values[i];
31        let y1 = y_values[i + 1];
32
33        if x >= x0 && x <= x1 {
34            return y0 + (y1 - y0) * (x - x0) / (x1 - x0);
35        }
36    }
37
38    panic!("Interpolation error: x-value out of interpolation range");
39}