function [monthly_payment] = bisection(m_0,m_1)
%function [monthly_payment] = bisection(m_0,m_1)
% m_0 = guess for monthly payment
% m_1 = guess for monthly payment
% initialize appropriate variables, for example
y = 25; % 25 year loan
r = 4.3; % 4.3% interest rate
L = 100000; % initial loan of $100,000
b_0 = get_balance(L,r,y,m_0);
if (abs(b_0) < 0.01) % if the balance either way is less than one cent
monthly_payment = m_0;
return; % return the monthly payment without evaluating the rest of the function
end
b_1 = get_balance(L,r,y,m_1);
if (abs(b_1) < 0.01) % if the balance either way is less than one cent
monthly_payment = m_1;
return; % return the monthly payment without evaluating the rest of the function
end
% check to make sure initial guesses are reasonable, otherwise return error
if (b_0*b_1 > 0)
error(['initial guess must bracket the root, '...
'i.e. one negative balance, one positive balance'])
end
% actual bisection loop
iterate = 1;
fprintf('iterate, interval, uncertainty\n')
fprintf('------------------------------\n')
fprintf('0, [%.2f %.2f], %.2f \n',m_0,m_1,abs(m_1-m_0)/2);
% while we don't have an estimate to the nearest cent
while ( abs(m_1-m_0) > 0.01 )
% calculate midpoint of interval
m_mid = (m_0 + m_1) / 2;
% evaluate balance using m_mid
b_mid = get_balance(L,r,y,m_mid);
% if b_mid is less than one cent return b_mid and exit
if ( abs(b_mid) < 0.01)
monthly_payment = m_mid;
return;
elseif ( (b_mid * b_0) > 0 )
% if b_mid and b_0 are same sign, replace m_0 with m_mid
b_0 = b_mid;
m_0 = m_mid;
else
% replace m_1;
b_1 = b_mid;
m_1 = m_mid;
end
fprintf('%d, [%.2f %.2f], %.2f \n',iterate,m_0,m_1,abs(m_1-m_0)/2);
iterate = iterate + 1;
end
% when loop completes, return the average of m_0 and m_1
monthly_payment = (m_0 + m_1)/2;
fprintf('monthly payment amount should be $%.2f \n', monthly_payment);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [ balance ] = get_balance(loan_amount,rate,year, monthly_payment)
% function [ balance ] = get_balance(loan_amount,rate,year,monthly_payment)
% loan_amount = initial loan amount (in dollars)
% rate = annual interest rate (in percent)
% year = length of loan (in years)
% monthly_payment = monthly payment (in dollars)
% Set the balance initially to be the initial loan amount
balance = loan_amount;
% for each month of the loan
for k = 1 : year*12
balance = balance * (1 + rate/100/12) - monthly_payment;
end