001// ***************************************************************************************************************************
002// * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements.  See the NOTICE file *
003// * distributed with this work for additional information regarding copyright ownership.  The ASF licenses this file        *
004// * to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance            *
005// * with the License.  You may obtain a copy of the License at                                                              *
006// *                                                                                                                         *
007// *  http://www.apache.org/licenses/LICENSE-2.0                                                                             *
008// *                                                                                                                         *
009// * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an  *
010// * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the        *
011// * specific language governing permissions and limitations under the License.                                              *
012// ***************************************************************************************************************************
013package org.apache.juneau.utils;
014
015/**
016 * A simple weighted average of numbers.
017 */
018public class WeightedAverage {
019   private Double value = 0d;
020   private int weight = 0;
021
022   /**
023    * Add a number with a weight to this average.
024    *
025    * @param w The weight of the new value.
026    * @param v The new value.
027    * @return This object (for method chaining).
028    */
029   public WeightedAverage add(int w, Number v) {
030      if (v != null) {
031         try {
032            double w1 = weight, w2 = w;
033            weight = Math.addExact(weight, w);
034            if (weight != 0) {
035               value = (value * (w1/weight)) + (v.floatValue() * (w2/weight));
036            }
037         } catch (ArithmeticException ae) {
038            throw new ArithmeticException("Weight overflow.");
039         }
040      }
041      return this;
042   }
043
044   /**
045    * Returns the weighted average of all numbers.
046    *
047    * @return The weighted average of all numbers.
048    */
049   public double getValue() {
050      return value;
051   }
052}