Hello.
I'm implementing a Percentile function which requires also a linear interpolation function. I'm aiming to make them generic for integers and floats. The interpolation function works fine when called from it's test but breaks compilation when called from the percentile function.
pub fn interpolate_linear<T: Add<Output=T> + Sub<Output=T> + Debug + Copy>(a: &T, b: &T, how_far_from_a_to_b: f64) -> f64
where f64: From<T> {
let a = f64::from(*a);
let b = f64::from(*b);
a + (how_far_from_a_to_b * (b - a))
}
pub fn percentile<T: Add<Output=T> + Sub<Output=T> + PartialOrd + Debug + Copy>(data_set: &Vec<T>, n: f64) -> f64 where f64: From<T> {
let rank = n * (data_set.len() as f64 -1f64) + 1f64;
println!("Rank = {}", rank);
let below = rank.floor() as usize;
let above = rank.floor() as usize + 1;
let lower_value = f64::from(data_set[below]);
let higher_value = f64::from(data_set[above]);
interpolate_linear(&lower_value, &higher_value, n);
}
And the error this produces is:
error[E0308]: mismatched types
--> src/statistics.rs:21:24
|
21 | interpolate_linear(&lower_value, &higher_value, n)
| ^^^^^^^^^^^^ expected type parameter, found f64
|
= note: expected type `&T`
found type `&f64`
error[E0308]: mismatched types
--> src/statistics.rs:21:38
|
21 | interpolate_linear(&lower_value, &higher_value, n)
| ^^^^^^^^^^^^^ expected type parameter, found f64
|
= note: expected type `&T`
found type `&f64`
I have the following test which works fine:
#[test]
fn test_interpolate_with_f32() {
let result = interpolate_linear(&3f32, &5f32, 2f64);
println!("test_interpolate_with_i32 result: {:?}", result);
assert_eq!(result, 7f64);
}
What gives?