SRM258 autoLoan

Auto dealerships frequently advertise tempting loan offers in order to make it easier for people to afford the “car of their dreams”. A typical sales tactic is to show you various cars, and then talk in terms of what your monthly payment would be, to say nothing of how much you are actually paying for the car, how much interest you pay, or how long you have to make payments.

A typical auto loan is calculated using a fixed interest rate, and is set up so that you make the same monthly payment for a set period of time in order to fully pay off the balance. The balance of your loan starts out as the sticker price of the car. Each month, the monthly interest is added to your balance, and the amount of your payment is subtracted from your balance. (The payment is subtracted after the interest is added.) The monthly interest rate is 1/12 of the yearly interest rate. Thus, if your annual percentage rate is 12%, then 1% of the remaining balance would be charged as interest each month.

You have been checking out some of the cars at your local dealership, TopAuto. An excited salesman has just approached you, shouting about how you can have the car you are looking at for a payment of only monthlyPayment for only loanTerm months! You are to return a double indicating the annual percentage rate of the loan, assuming that the initial balance of the loan is price.

#include <algorithm>
#include <cmath>
using namespace std;

class AutoLoan {
    double interestRate(double price, double monthlyPayment, int loanTerm){
        double balance;
        double high = 100, low = 0, mid = 0;

        while((1e-9 < high - low) && (1e-9 < (high -low)/high)){
            balance = price;
            mid = (high + low) / 2;

            for (int j=0; j<loanTerm; j++){
                balance *= mid / 1200 + 1;
                balance -= monthyPayment;
            }
            if (0 < balance) high = mid;
            else low = mid;
        }
        return mid;
    }
}

mid = (high + low) / 2; としてから、highとlowの差が限りなく小さくなるまでwhileで繰り返し処理を行う。
1e-2は0.01で、1e-9は0.000000001
“1e-n”という表現は覚えておいて損はなさそう