rust_3d/
distances_nd.rs

1/*
2Copyright 2017 Martin Buck
3
4Permission is hereby granted, free of charge, to any person obtaining a copy
5of this software and associated documentation files (the "Software"),
6to deal in the Software without restriction, including without limitation the
7rights to use, copy, modify, merge, publish, distribute, sublicense,
8and/or sell copies of the Software, and to permit persons to whom the Software
9is furnished to do so, subject to the following conditions:
10
11The above copyright notice and this permission notice shall
12be included all copies or substantial portions of the Software.
13
14THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
18DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
20OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21*/
22
23//! Distances between objects in ND space
24
25use crate::*;
26
27//------------------------------------------------------------------------------
28
29/// Returns the distance between two IsND in case their number of dimensions match
30pub fn dist_nd<P, U>(p1: &P, p2: &U) -> Result<f64>
31where
32    P: IsND,
33    U: IsND,
34{
35    sqr_dist_nd(p1, p2).map(|x| x.sqrt())
36}
37
38/// Returns the squared distance between two IsND in case their number of dimensions match
39pub fn sqr_dist_nd<P, U>(p1: &P, p2: &U) -> Result<f64>
40where
41    P: IsND,
42    U: IsND,
43{
44    if P::n_dimensions() != U::n_dimensions() {
45        return Err(ErrorKind::DimensionsDontMatch);
46    }
47
48    let mut result: f64 = 0.0;
49    for i in 0..P::n_dimensions() {
50        if let (Ok(val1), Ok(val2)) = (p1.position_nd(i), p2.position_nd(i)) {
51            result += (val1 - val2).powi(2);
52        } else {
53            return Err(ErrorKind::IncorrectDimension);
54        }
55    }
56    Ok(result)
57}