Compute weighted averages for large numbers

Posted by Travis on Stack Overflow See other posts from Stack Overflow or by Travis
Published on 2010-05-30T07:01:09Z Indexed on 2010/05/30 7:12 UTC
Read the original article Hit count: 288

Filed under:
|
|

I'm trying to get the weighted average of a few numbers. Basically I have:

Price    - 134.42
Quantity - 15236545

There can be as few as one or two or as many as fifty or sixty pairs of prices and quantities. I need to figure out the weighted average of the price. Basically, the weighted average should give very little weight to pairs like

Price    - 100000000.00
Quantity - 3

and more to the pair above.

The formula I currently have is:

((price)(quantity) + (price)(quantity) + ...)/totalQuantity

So far I have this done:

        double optimalPrice = 0;
        int totalQuantity = 0;
        double rolling = 0;
        System.out.println(rolling);

        Iterator it = orders.entrySet().iterator();
        while(it.hasNext()) {
            System.out.println("inside");
            Map.Entry order = (Map.Entry)it.next();
            double price = (Double)order.getKey();
            int quantity = (Integer)order.getValue();
            System.out.println(price + " " + quantity);

            rolling += price * quantity;
            totalQuantity += quantity;
            System.out.println(rolling);
        }
        System.out.println(rolling);
        return totalQuantity / rolling;

The problem is I very quickly max out the "rolling" variable.

How can I actually get my weighted average?

Thanks!

© Stack Overflow or respective owner

Related posts about java

Related posts about average