用存储在两个数组中的数字和权重计算加权平均值 [英] Calculate weighted average with numbers and weights stored in two arrays

查看:409
本文介绍了用存储在两个数组中的数字和权重计算加权平均值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于堆栈溢出,已经存在有关如何计算[Int:Int]字典的加权平均值的问题,包括使用reduce的奇特方法.但是我现在将数字和权重存储在两个数组中.不能保证数字相同. 什么是 Swift 方式?是否可以使用reduce之类的Swift功能?我希望有一种不使用for循环的方式.谢谢!

There are already questions on Stack Overflow on how to calculate weighted mean of an [Int:Int] dictionary, including fancy ways using reduce. But I now have the numbers and weights stored in two arrays. The numbers are not guaranteed to be identical. What is the Swift way to do this? Is it possible using Swift features like reduce? I wish there is a way that does not use a for loop. Thanks!

let numbers = [1, 2, 4, 3, 2]
let weights = [10, 20, 30, 15, 25]

推荐答案

没有for循环:

func weightedAverage(values: [Double], weights: [Double]) -> Double {
    precondition(values.count > 0 && values.count == weights.count)

    let totalWeight = weights.reduce(0.0, +)
    precondition(totalWeight > 0)

    return zip(values, weights)
            .map { $0 * $1 }
            .reduce(0.0, +) / totalWeight
}

let avg = weightedAverage(values: [1, 2, 4, 3, 2], weights: [10, 20, 30, 15, 25])
print(avg)

这篇关于用存储在两个数组中的数字和权重计算加权平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆