2

I'm writing a Java code to Calculate the amount of Quantity we have to buy so that the weighted average is equal to the Target avg Price.

Example : Lets say a product p

Q1 = 310; // This much quantity I already have.

P1 = 16.40; // I bought Q1 quantity @ P1 price.

P2 = 15.00; // Current Market Price for Quantity.

P3 = 15.10; // Target Avg Price. I have to bring my Avg price to his price.

Q2 = ? // How many of product p to be bought at price P2. So that my avg price is equal to P3.

I'm not able to figure out a direct formula for this.

So far I have tried this :

void int getQuantity(Q1,P1,P2,P3) 
{
    int i = 0;
    while(true) 
    {
        double calcPrice = ((Q1*P1)+(i*P2))/(Q1+i);

        // If Calculated price equals to Target Price, break out of loop
        if(calcPrice == P3) {
            break;
        }
        // if values not same Increment i by 1.
        ++i;
    }
    return i;
}

Help will be appreciated.

Thanks

ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
maddy man
  • 89
  • 4
  • 10

1 Answers1

2

The math bhind this is pretty simple. The formula is:

Q1 * P1 + Q2 * P2
----------------   =   P3
    Q1 + Q2

If you solve this by Q2 you'll have:

      Q1 * (P1 - P3)
Q2 = ---------------
        (P3 - P2)

In code this would be:

double Q2 = Q1 * (P1-P3) / (P3-P2);

The complete method has to cover things like P2 == P3 or P2 > P3. You could handle these cases like this (for example):

public double getQuantity(int Q1, double P1, double P2, double P3) throws IllegalArgumentException {
    if ((P1 > P3 && P3 > P2) || (P1 < P3 && P3 < P2))
        return Q1*(P1-P3)/(P3-P2);
    else if (P1 == P3)
        return 0;
    else
        throw new IllegalArgumentException("P3 has to be between P1 and P2!");
}
ParkerHalo
  • 4,341
  • 9
  • 29
  • 51
  • Thanks for quick reply. But this formula will not work if Current Price and Target Price are equal. That is P2 == P3. – maddy man Dec 09 '15 at 11:11
  • 2
    The reason for that is that it's not possible to reach the average price then. You'd have to buy an infinate amount to reach it ;) But i'll edit my post accordingly to help you with that issue – ParkerHalo Dec 09 '15 at 11:13
  • @Teepeemm you're right! I'll adapt my example according to your post! – ParkerHalo Dec 09 '15 at 15:32