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