Created
December 27, 2023 20:35
-
-
Save petergi/4a44168bebb3e438dc86f880bb1a3bab to your computer and use it in GitHub Desktop.
Calculates the weighted average of two or more numbers
This file contains hidden or 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
/// | |
/// | |
/// # Arguments | |
/// | |
/// * `nums`: | |
/// * `weights`: | |
/// | |
/// returns: f64 | |
/// | |
/// # Examples | |
/// | |
/// ``` | |
/// let average = weighted_average(&[1.0, 2.0, 3.0], &[0.6, 0.2, 0.3]); | |
/// println!("{}", average) | |
/// ``` | |
pub fn weighted_average(nums: &[f64], weights: &[f64]) -> f64 { | |
let mut sum = 0.0; | |
let mut weight_sum = 0.0; | |
for i in 0..nums.len() { | |
sum += nums[i] * weights[i]; | |
weight_sum += weights[i]; | |
} | |
sum / weight_sum | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment