首页 > 解决方案 > 让算法在 Rust 中同时使用 f32 和 f64 所需的 Rust 特征

问题描述

我正在尝试编写一个适用于f32和的通用线性插值器f64。我的代码如下:

#[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;
   |                           ^^^^^

我应该添加哪些特征才能使任何浮点类型与此泛型一起使用?更一般地说,需要什么特征才能使调用标准数值函数(如log, sin, )的通用数值函数exp成功编译?

标签: rusttraits

解决方案


推荐阅读