如何从数组中求平均值?

如果我有一个数组:

[0,4,8,2,5,0,2,6]

平均得到3.375。


当前回答

我希望Math.average(values),但没有这样的运气。

values = [0,4,8,2,5,0,2,6]
average = values.sum / values.size.to_f

其他回答

a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : a.reduce(:+)/a.size.to_f
=> 3.375

解决除零,整数除法,易于阅读。如果您选择让空数组返回0,则可以轻松修改。

我也喜欢这个变体,但是有点啰嗦。

a = [0,4,8,2,5,0,2,6]
a.empty? ? nil : [a.reduce(:+), a.size.to_f].reduce(:/)
=> 3.375

比.inject更快的解决方案是:

sum(0.0)/arr.size

参见这篇文章参考:https://andycroll.com/ruby/calculate-a-mean-average-from-a-ruby-array/

class Array
  def sum 
    inject( nil ) { |sum,x| sum ? sum+x : x }
  end

  def mean 
    sum.to_f / size.to_f
  end
end

[0,4,8,2,5,0,2,6].mean

打印数组。求和/数组。计数是我做到的方式

a = [0,4,8,2,5,0,2,6]
a.instance_eval { reduce(:+) / size.to_f } #=> 3.375

不使用instance_eval的版本如下:

a = [0,4,8,2,5,0,2,6]
a.reduce(:+) / a.size.to_f #=> 3.375