Hello, I just started learning c++ in school and had to make a calculator for compound interest with monthly payments. I wrote up the whole thing and I keep getting inf for the answer. What is usually wrong when you get inf as an answer? I'm using basic math formulas, no loops, ifs, or any of that stuff, just basic math. I can't figure out whats wrong in the program so any help would be great.
I don't think there is any answer to "What is usually wrong when you get inf as an answer?". A starting point would be to check that all variables are initialised (given a proper value) before you attempt to use them.
Beyond that, to give any answer without seeing your actual code would be pure speculation, I think.
It looks like there is a divide-by-zero which gives infinity as the result. But it isn't directly obvious.
I used these values:
fValue = 1000
irate = 2
time = 24
(I don't know whether these values are sensible)
Then we get this: pow((irate/icompnd),(icompnd * time))
= pow(0.1666666667, 24)
= 2.11042533E-19
Now if we evaluate the rest of the denominator:
(1.0 + 2.11042533E-19) - 1.0
= 0
No idea why you would want to add 1 and then subtract 1, but because of the limited precision of the floating point type, this evaluates to zero. Anything divided by zero gives infinity.
I suggest you re-check the algorithm. If necessary, work out an example on paper, using a calculator, and see if the calculations are doing what you want them to do.
i did do it on paper with a calculator first. The equation I used is
FV = PMT * ( ( (1 + i/n)^nt) - 1) / i/n )
and rewrote it as
PMT = (FV(i/n)) / (((1 + (i/n))^nt - 1)
because I need to find the deposit amounts. So did I write the equation in wrong?
n = icompnd
i = irate
fv = fValue
pmt = deposit
t = time
I see what your saying about the pow coming out as zero. I'm not sure why it comes out like that. When I use your numbers in the calculator (1 + (2/12))^24) it comes out as 40.43178835, which is right.
You've got this part translated into code incorrectly: (1 + (i/n))^nt, the 1 should be added before raising that number to the required power. But in the c++ code, you do the pow() first and add the 1.0 afterwards.