#interpolation #linear-interpolation #pair #sorting

interp1d

用 Rust 编写的简单、轻量级插值库

3 个不稳定版本

0.2.0 2022年10月11日
0.1.1 2022年7月22日
0.1.0 2022年7月22日

1736算法

每月 下载次数 38

MIT/Apache

18KB
312

interp1d: 用 Rust 编写的简单、轻量级插值库

该库旨在非常简单和轻量。核心 Interp1D 结构体接受一些 (x, y) 对,并具有简单的线性插值方法。与其他库不同,此库有两个核心特点

  1. 它拥有 (x, y) 对的所有权,并在内部对它们进行排序,使用二分搜索找到进行插值的两个相邻点。这防止了其他函数可能执行的排序/搜索操作。
  2. 它允许 xy 的类型不同。 x 可以是整数或浮点数,可以与 y 的类型不同(y 必须仍然是浮点数)。这允许在 1D 晶格上进行插值等操作。

简单用法

双精度浮点数的示例

use interp1d::Interp1d;


fn main() {

    // Data (already sorted)
    let x: Vec<f64> = vec![1.0, 2.0, 3.0];
    let y: Vec<f64> = vec![5.0, 3.0, 4.0];

    // Using `new_sorted` since data is already sorted
    let interpolator = Interp1d::new_sorted(x, y).unwrap();

    // Points at which we wish to interpolate
    let x_interp = vec![1.5, 2.5];

    // Intepolate with checked fn
    let y_interp: Vec<f64> = x_interp
        .iter()
        .map(|&x| interpolator.interpolate_checked(x))
        .collect::<Result<Vec<f64>, _>>()
        .unwrap(); // all points are in the domain in this example
    
    println!("y_interp = {y_interp:?}");
    // Output:
    // y_interp = [4.0, 3.5]
}

x 作为 usize 的示例

use interp1d::Interp1d;


fn main() {

    // Data (already sorted)
    let x: Vec<usize> = vec![1, 3, 5];
    let y: Vec<f64> = vec![5.0, 3.0, 4.0];

    // Using `new_sorted` since data is already sorted
    let interpolator = Interp1d::new_sorted_int(x, y);

    // Points at which we wish to interpolate
    let x_interp = vec![2, 4];

    // Intepolate with checked fn
    let y_interp: Vec<f64> = x_interp
        .iter()
        .map(|&x| interpolator.interpolate_checked(x))
        .collect::<Result<Vec<f64>, _>>()
        .unwrap(); // all points are in the domain in this example
    
    println!("y_interp = {y_interp:?}");
    // Output:
    // y_interp = [4.0, 3.5]
}

依赖项

~0.5–1MB
~22K SLoC