Search code examples
javalogarithm

Using logarithms


I am trying to to an equation to solve for the amount of time left on a loan based on a specific payment amount (above the normal amount).

The equation is:

nRemaining = ((-log(1-(interestRate / 12) * value2 / value3)) / (log (1+ (interestRate / 12))));

Now obviously this does not work, because I am unsure how to input logarithms.


Solution

  • Your code will work fine, provided a few conditions are met:

    • If you have to use log that way, place this statement above your class:

      import static java.lang.Math.log;
      

      Otherwise, use Math.log() everywhere else you see log.

      Technically you don't have to import anything in java.lang, but this is known as a static import - something that should only be done on occasion, and allows you to write your statement a lot cleaner.

    • Make sure that all of your values are of type double. Otherwise, you'll get integer division, which can lead to NaN for some otherwise inexplicable reason.