rust - 让算法在 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
成功编译?
解决方案
推荐阅读
- javascript - 在 Javascript 对象数组中查找并删除第一个匹配元素
- amazon-web-services - 如何在 terraform 中为 IAM 用户启用控制台登录
- mysql - 如何根据其他表中的值编写更新
- php - 如何处理与 Laravel 中的模型不同的映射的请求
- ios - Travis CI 问题:在提到的工作区中找不到指定的方案
- python - 在 jquery prepend 函数中给出模板标签
- javascript - d3.js - 如何实现指针式的移动行为?
- php - WordPress update_user_meta 确实适用于变量
- c# - 我如何在数组中提供 AD 作为正确答案,而不是 0-3?
- spring - 使用 Spring Integration 移入 GCP 存储后如何从本地目录中删除文件