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 to0.01, which is exactly what we want. Therefore, let's backtrack:The debugger tells us that
principalevaluates to-0.004166666666666652andntevaluates to-360. What you are therefore trying to calculate is the following:which is mathematically equivalent to
Now, if you just look at
with
Math.pow(-0.004166666666666652, 360), you are taking a fraction whose value is between-1.0and0.0and raise that to a very high power (in this case360). 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 approaches0.0the higher the exponent is (mathematically speakingn >> 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:
which prints
0.7761734043586468for both, the example from the video and the result of the code.