Skip to content

Instantly share code, notes, and snippets.

@petergi
Created December 27, 2023 20:35
Show Gist options
  • Save petergi/4a44168bebb3e438dc86f880bb1a3bab to your computer and use it in GitHub Desktop.
Save petergi/4a44168bebb3e438dc86f880bb1a3bab to your computer and use it in GitHub Desktop.
Calculates the weighted average of two or more numbers
///
///
/// # 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