0

I keep getting the wrong result for multiplication, it only compounds with more iterations, but at one it returns 500 instead of 495.

I have tried initializing the variable and flipping the terms but it is not helping.

void output_short_format(double loan_amount, double interest_rate, double term_years){
    double payment,interest=0,total,months,temp;    

    temp = loan_amount;
    interest_rate /= 12;
    months = 12 * term_years;
    payment = loan_amount * interest_rate * (pow(1+interest_rate,months)/(pow(1+interest_rate,months)-1));

    for(int i=1;i<=months;i++){
    interest += temp*interest_rate;
    temp -= payment;
    }

I expect 150000 * 0.0033 to produce 495 not 500

Kyler
  • 1
  • 1
    Maybe something like https://stackoverflow.com/questions/588004/is-floating-point-math-broken – Mark Ransom Jul 21 '19 at 00:29
  • ^ that's probably it, double has only 15-17 decimal digits of accuracy. – Dave S Jul 21 '19 at 00:35
  • Is there another solution to this problem? – Kyler Jul 21 '19 at 00:35
  • 1
    Dealing with loss of precision is a complicated topic. Sometimes you can reduce the loss by re-ordering your operations so that you avoid mixing numbers with very different exponents (like 150000 and .0033) as much as possible. That is, operate on the "big" numbers separately from the "little" numbers when you can. For example, in addition add up all the little numbers first, only then add that one sum to the big number. – Dave S Jul 21 '19 at 00:39

0 Answers0