fluent_data/
space.rs

1//! This module defines the necessary functions to run the algorithm for data points that belong to R^n.
2//!  - the Euclidian distance function
3//!  - the vectorial barycentre function
4
5/// A point in R^n.
6pub type RealPoint = Vec<f64>;
7
8/// Conputes the square of the Euclidian distance in R^n.
9pub fn euclid_dist(p1: &RealPoint, p2: &RealPoint) -> f64 {
10    p1.iter()
11        .zip(p2)
12        .map(|(x1, x2)| {
13            let d = x1 - x2;
14            d * d
15        })
16        .sum()
17}
18
19/// Computes weighted center in a R^n vector space.
20pub fn real_combine(p1: &RealPoint, w1: f64, p2: &RealPoint, w2: f64) -> RealPoint {
21    let w = w1 + w2;
22    p1.iter()
23        .zip(p2)
24        .map(|(x1, x2)| (x1 * w1 + x2 * w2) / w)
25        .collect()
26}
27
28#[cfg(test)]
29mod tests {
30    use crate::space::*;
31
32    #[test]
33    fn test_euclid_dist() {
34        let d = euclid_dist(&vec![1., 1.], &vec![0., 0.]);
35        assert_eq!(2., d);
36        let d = euclid_dist(&vec![1., 3.], &vec![-1., 4.]);
37        assert_eq!(5., d);
38    }
39
40    #[test]
41    fn test_real_combine() {
42        let c = real_combine(&vec![1., -1.2], 1., &vec![2.5, -0.9], 2.);
43        assert_eq!(vec![2., -1.], c);
44    }
45}