-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
0c2f4d9
commit ed80173
Showing
3 changed files
with
50 additions
and
6 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
// Author : cyrixninja | ||
// Calculate the Euclidean distance between two vectors | ||
// Wikipedia : https://en.wikipedia.org/wiki/Euclidean_distance | ||
|
||
pub fn euclidean_distance(vector_1: &Vector, vector_2: &Vector) -> f64 { | ||
// Calculate the Euclidean distance using the provided vectors. | ||
let squared_sum: f64 = vector_1 | ||
.iter() | ||
.zip(vector_2.iter()) | ||
.map(|(&a, &b)| (a - b).powi(2)) | ||
.sum(); | ||
|
||
squared_sum.sqrt() | ||
} | ||
|
||
type Vector = Vec<f64>; | ||
|
||
#[cfg(test)] | ||
mod tests { | ||
use super::*; | ||
|
||
// Define a test function for the euclidean_distance function. | ||
#[test] | ||
fn test_euclidean_distance() { | ||
// First test case: 2D vectors | ||
let vec1_2d = vec![1.0, 2.0]; | ||
let vec2_2d = vec![4.0, 6.0]; | ||
|
||
// Calculate the Euclidean distance | ||
let result_2d = euclidean_distance(&vec1_2d, &vec2_2d); | ||
assert_eq!(result_2d, 5.0); | ||
|
||
// Second test case: 4D vectors | ||
let vec1_4d = vec![1.0, 2.0, 3.0, 4.0]; | ||
let vec2_4d = vec![5.0, 6.0, 7.0, 8.0]; | ||
|
||
// Calculate the Euclidean distance | ||
let result_4d = euclidean_distance(&vec1_4d, &vec2_4d); | ||
assert_eq!(result_4d, 8.0); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters