使算法在Rust中同时使用f32和f64所需的Rust特征

时间:2018-09-25 03:11:00

标签: rust traits

我正在尝试编写一种在f32f64上都可以使用的通用线性内插器。我的代码如下:

#[derive(Debug)]
pub struct LinearInterpolation<Real>
{
    pub data: Vec<Real>,
    pub start_time: Real,
    pub time_step: Real,
}

use std::convert::From;

impl<Real> LinearInterpolation<Real>
    where Real: std::ops::Div<Output = Real> + std::ops::Sub<Output=Real> + std::cmp::PartialOrd + Default + Copy
{
    fn at(&self, time: Real) -> Real {
        let diff: Real = Real::from(time - self.start_time);
        if diff < default::Default() {
            panic!("This is really bad!");
        }
        let index = diff/self.time_step;
        let index = index.floor() as usize;
        if index - 1 >= self.data.len() {
            panic!("Index is too large!");
        }
        let y0 = self.data[index];
        let y1 = self.data[index+1];
        let slope = (y1 - y0)/self.time_step;
        y0 + slope*diff
    }
}

但是,我无法使用index.floor()方法。编译器错误消息是

error[E0599]: no method named `floor` found for type `Real` in the current scope
  --> src/lib.rs:23:27
   |
23 |         let index = index.floor() as usize;
   |                           ^^^^^

我应该添加哪些特征以使任何浮点类型都可以与此泛型一起使用?而且更普遍的是,需要什么特征才能成功地调用诸如logsinexp之类的标准数字函数的通用数字函数?

0 个答案:

没有答案