• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Summary: Calculate average where sum exceed double limits

What is a good solution for calculating an average where the sum of all values exceeds a double's limits?

According to the highest vote in:

http://stackoverflow.com/questions/1930454/what-is-a-good-solution-for-calculating-an-average-where-the-sum-of-all-values-e

 

You can calculate the mean iteratively. This algorithm is simple, fast, you have to process each value just once, and the variables never get larger than the largest value in the set, so you won't get an overflow.

1 double mean(double[] ary) {
2   double avg = 0;
3   int t = 1;
4   for (double x : ary) {
5     avg += (x - avg) / t;
6     ++t;
7   }
8   return avg;
9 }

 

posted @ 2017-01-31 01:38  neverlandly  阅读(282)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3