I'm trying to create a mortgage calculator in Java, but I'm having trouble with a math problem. In essence, I need to raise to power a double but can't. I also tried (Math. pow) but it returns infinite since my exponent is a negative integer. Does anyone have any recommendations?
int n = 12;
int t = 30;
double r = 0.05;
int nt = n * t; // = 360
nt = -nt; // = -360
double principal = 1.0 - (1.0 + r / n); // = -0.004166666666666652
double result = Math.pow(principal, nt); // = Infinity
System.out.println(result);
Is there a way to raise Principal
to the power of nt
?
Your issue seems to lie in your maths, not the call to Math.pow()
, which works perfectly fine for negative exponents: Math.pow(10, -2)
leads to 0.01
, which is exactly what we want. Therefore, let's backtrack:
The debugger tells us that principal
evaluates to -0.004166666666666652
and nt
evaluates to -360
. What you are therefore trying to calculate is the following:
double result = Math.pow(-0.004166666666666652, -360); // = Infinity
which is mathematically equivalent to
double result = 1.0 / Math.pow(-0.004166666666666652, 360) // = Infinity
Now, if you just look at Math.pow(-0.004166666666666652, 360)
, you are taking a fraction whose value is between -1.0
and 0.0
and raise that to a very high power (in this case 360
). What happens to a fraction that is in the interval ]-1.0; 1.0[
and that is raised to such a high power is that it approaches 0.0
the higher the exponent is (mathematically speaking with n >> 0
).
Your math therefore becomes
Your math therefore must be wrong somewhere, and in fact, if you look at the video that you linked in a comment, the formula that you need to use is the following:
but what you implemented is
I hope you see where the issue is now and wish you good luck with the exercise :)
Edit: Using the correct formula, your code should look like this:
int n = 12;
int t = 30;
double r = 0.05;
double result = 1.0 - Math.pow(1.0 + r / n, -n * t);
System.out.println(result);
// Example from the video for comparison
System.out.println(1.0 - Math.pow(1.00416666666666666666, -360));
which prints 0.7761734043586468
for both, the example from the video and the result of the code.