I just cannot find the correct answer, so here is my problem: I want to be able to calculate the indexation (a positive or negative percentage) over a price and period.
Expectations:
Case #1
Price : 1.000,00
Indexation percentage : 5%
Calculation over 5 years with positive percentage:
1. 1000 x 5^0 = 1000
2. 1000 x 5^1 = 1050
3. 1000 x 5^2 = 1102,50
4. 1000 x 5^3 = 1157.625
5. 1000 x 5^4 = 1215,50625
Case #2
Price : 1.000,00
Indexation percentage : -5%
Calculation over 5 years with negative percentage:
1. 1000 x -5^0 = 1000
2. 1000 x -5^1 = 950
3. 1000 x -5^2 = 902,50
4. 1000 x -5^3 = 857,375
5. 1000 x -5^4 = 814,50625
Results:
And this negative percentage goes wrong, because my java code prints this out:
1000
-5000
-125000
15625000
1175690408
My code is pretty simple, i think:
BigDecimal percentageValue = new BigDecimal("-5");
BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE);
BigDecimal price = new BigDecimal("1000");
for (int i = 0; i < 5; i++)
{
price = price.multiply(indexation.pow(i));
System.out.println(price.intValue());
}
Solution:
static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
public static void main(String[] args)
{
BigDecimal percentageValue = new BigDecimal("-5");
BigDecimal indexation = percentageValue.divide(ONE_HUNDRED).add(BigDecimal.ONE);
BigDecimal price = new BigDecimal("1000");
for (int i = 0; i < 5; i++)
{
BigDecimal result = price.multiply(indexation.pow(i));
System.out.println(result);
}
}
You should multiply by
1 + percents/100, 1% is 1/100.Note that 5% intrest over one years makes 1000 become 1050 and not 5000
so for 5%:
1.05^nand for negative [-5%]:0.95^nYou can use BigDecimal to do it, since the numebrs are not integers.
EDIT: [as respond to editted question] Your editted code does not produce the output you gave [assuming
ONE_HUNDREDis initialized properly], however it still has a new issue:look at the second iteration, you already set
price = price * indexation^1When you multiply it again with
indexation^i[i==2] you get a wrong result!A solution could be one of those:
pow()here, just multiply each iteration with the indexation.price, hold the result ofprice.multiply(indexation.pow(i)in a new temp variable – and print it.