2

So for my C# programming class I have to calculate the number of months it would take to pay off a credit card balance given the balance, monthly payment and APR.

Here is the formula we were given to interpret:

Mathematical formula

Here is the C# version I made:

months = (double)decimal.Divide(-1, 30) * (
  Math.Log(1 + (double)(balance / payment) * (1 - Math.Pow((1 + (apr / 365)), 30)))
    / Math.Log(1 + (apr / 365))
);

It works for every example I've tried, except one, which is specified in a question I need to have the answer for:

How many months will it take Alice to pay off a $7,500.00 balance if the APR value is 0.22 and she pays $125.00 per month?

The output of which looks like:

Enter the credit card balance (example: 10000.00)
7500
Enter the monthly payment amount (example: 250.00)
125
Enter the annual percentage rate (example: 0.15)
0.22
It will take NaN months to pay off the balance.
Goodbye! Press any key to exit.

In my investigations, I plugged the formula into WolframAlpha and it returns two different values (http://bit.ly/1LQSsEx) perhaps this has something to do with it, but I am new to C# and have reached the end of my knowledge.

What is happening here, and how do I fix it?

Martin Liversage
  • 104,481
  • 22
  • 209
  • 256
zuddsy
  • 2,455
  • 2
  • 13
  • 19
  • 1
    That line of c# isn't very readable. I'd break it up. It will help you debug. [Code should be written for humans to read first and computers to read second](http://stackoverflow.com/a/522907/542251) – Liam Sep 25 '15 at 08:03
  • 1
    I'm, guessing that if wolfram gives you a complex number as a result, that it means, that there is no real solution for your equation probably log is out of its domain, or something like that... so that would be the reason for `NaN` – Matyas Sep 25 '15 at 08:07
  • Consider changing your equiatation into an expression, e.g.: ``Expression> months = (b, p, i) => (-1 / 30d) * ( Math.Log(1 + (b / p) * (1 - Math.Pow(1 + i, 30))) / Math.Log(1 + i) );`` – Binkan Salaryman Sep 25 '15 at 08:37

1 Answers1

3

the result of the following code yields a negative number.

1 + (double)(7500 / 125) * (1 - Math.Pow((1 + (0.22 / 365)), 30))

Math.Log for obvious reasons only works with numbers > 0

that's what giving you a NaN.

Liam
  • 27,717
  • 28
  • 128
  • 190
Dbuggy
  • 901
  • 8
  • 16
  • Ah! Thank you. I wrapped it in Math.Abs and now I am getting the output like I should. Hopefully, this isn't considered a terrible solution! Should I wrap the other Math.Log function with Abs as well? Edit: Actually nevermind, don't see why I'd need to, as the input shouldn't be less than zero in any case. – zuddsy Sep 25 '15 at 08:09