Least square method - how to improve this code?
Hi,
I implemented the least square linear regression method. My code works and does what it is supposed. But I always have a feeling like it could be written in a much better way.
So to see how more experienced Rust programmers would write it, how could I improve this code:
fn least_square_slope<T>(points: &Vec<(T,T)>) where T: num::traits::ToPrimitive {
let (x_mean, y_mean): (f64, f64) = (
points.iter().fold(0f64, |acc, ref point| {
acc + point.0.to_f64().unwrap()
}
) / (points.len() as f64),
points.iter().fold(0f64, |acc, ref point| {
acc + point.1.to_f64().unwrap()
}
) / (points.len() as f64)
);
let mut sum_x_diff_squared = 0f64;
let mut sum_x_diff_y_diff = 0f64;
for point in points {
let x_diff = point.0.to_f64().unwrap() - x_mean;
let y_diff = point.1.to_f64().unwrap() - y_mean;
sum_x_diff_y_diff += x_diff * y_diff;
sum_x_diff_squared += x_diff.powi(2);
}
let slope = sum_x_diff_y_diff / sum_x_diff_squared;
println!("Slope: {}", slope);
}
Any suggestions are appreciated :)
Posted Jun 7, 2015, 7:55 AM UTC
Nothing related to the numerical algorithm, more of a Rust thing: Please avoid functions that take a
&Vec<T>as parameter. Prefer&[T]instead. It's more general.&Vec<T>coerces to&[T]due toVec<T>implementingDeref<[T]>, so, you don't even have to change the code where you invoke the function.In this case, you could also take an iterator. For example:
But this may be overkill. If you always have the (x,y) pairs in an array, a function parameter of type
&[(f64,f64)]should suffice and save you the additional.iter().cloned()at the call site.Noted, I will not do it again ;)
Is
&[T]the equivalent for arrays? What does indirection mean?The difference between
&Vec<T>and&[T]is that&Vec<T>can only refer to a completeVecwhile&[T]can refer to a subslice of aVec's elements or something that is not even relaved toVecat all, for example some slice of a "raw array" of known size. The reason we haveVec<T>is because we can't use[T]directly since[T]is a dynamically-sized type. But such types behind some kind of "indirection" (pointer, reference, box) are fine. Internally, Vec<T> also just stores a pointer to its elements along with some length and capacity information. But it's implemented in such a way that it feels like its elements are "inside" theVec. :)It could be even more general by accepting an
IntoIterator. Then you won't have to change code at the call sites.IntoIteratoris cool, yes. But in this case it would not help much at the call site because a borrowed slice/Vec will only convert into an iterator over borrowed items and a Vec'sIntoIteris notClone.Are you sure about the borrowed slice part?
Yes.
What would I have to change from @sellibitze's answer to make it work with
IntoIterator? I tried multiple things, but always get an error like:The idea is the following:
so that it does some conversions for you to make it a little more convenient.
But this function is not very useful in your case because you don't have any types that actually fit these requirements. The standard provides the following
IntoIterator-based conversions that are relevant here:Vec<T>T&Vec<T>&T&[T]&T&[T;N]&TThe error you got is due to raw arrays not implementing
IntoIterator. You would have to borrow it first.Of course, you could change the other function to expect a
&(f64,f64)as item type to make thisIntoIteratorthing work for borrowed slices but that would be more restricting which is why I intentionally usedItem=(f64,f64). You can create these kinds of values on-the-fly, for example as a result ofmap.But an additional function like this:
seems like a good idea because these kinds of slices are common.
Very nice explanation! Thank you :)
How would that affect the body of the function? I have tried, but I can't make it work
Ow woaw, this looks so much more beautiful ! Thank you very much, I would never have thought about this myself :)
Thanks. :)