javamathcalculatorpow

How can i perform a "raise to the pow" for my Java Mortgage Code


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?


Solution

  • 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 limit of x^n with x approaching -0 = 0 with n >> 0).

    Your math therefore becomes

    result = 1 / -0.004166666666666652^360 approximately equals 1 / 0 approximately equals Infinity

    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:

    result = 1 - (1 + r / n)^-nt

    but what you implemented is

    result = (1 - (1 + r / n))^-nt

    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.