hmath.py 文件源码

python
阅读 30 收藏 0 点赞 0 评论 0

项目:luckyhorse 作者: alexmbird 项目源码 文件源码
def weighted_avg_and_std(values, weights=None):
  '''
  Return the weighted average and standard deviation.

  `values`  - np.ndarray of values to average.
  `weights` - Optional np.ndarray of weights.  Otherwise all values are assumed
              equally weighted.

  Note the helpful np.fromiter() function, helpful building arrays.
  '''
  if not isinstance(values, np.ndarray):
    raise TypeError("Values must be an np.array")
  if len(values) == 0:
    raise ValueError("Can't calculate with no values")
  if weights is not None:
    if not isinstance(weights, np.ndarray):
      raise TypeError("Weights must be None or an np.array")
    if len(values) != len(weights):
      raise ValueError("Length of values and weights differ")

  average = np.average(values, weights=weights)
  variance = np.average((values-average)**2, weights=weights)  # Fast and numerically precise
  return (average, math.sqrt(variance))
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号