It's ugly, and I'm not sure if "midpoint algorithm" is the actual name of the algorithm. I remember doing this for my Numerical Methods course.
% Determines the effective annual yield (APY) given a principal amount,
% a final amount, and number of years.
clear
clc
P = input('Enter principal (beginning) amount: ');
Y = input('Enter final (ending) amount: ');
n = input('Enter number of years: ');
% Need to calculate r (APY)
% Use mid-point algorithm
% Formula is Y = P(1+r)^n
% Assume range of r from 0 to 5 (0 % to 300%)
r_min = 0;
r_max = 5;
current_guess = r_min;
Y_temp = P*(1+current_guess)^n;
num_guesses = 1;
tic
while Y_temp ~= Y
if (Y_temp > Y*0.9999) && (Y_temp < Y*1.0001)
break
end
if Y_temp < Y
next_guess = (current_guess + r_max)/2;
else next_guess = (r_min + current_guess)/2;
end
Y_temp = P*(1+next_guess)^n;
if Y_temp < Y
r_min = next_guess;
else r_max = next_guess;
end
current_guess = next_guess;
num_guesses = num_guesses + 1;
Y_temp = P*(1+current_guess)^n;
end
toc
r = current_guess;
effective_apy = r*100;
output_str = ['Effective APY = ',num2str(effective_apy),'%'];
num_guess_str = ['With ',num2str(num_guesses),' guesses.'];
disp(output_str)
disp(num_guess_str)
No comments:
Post a Comment