Monday, June 10, 2013

Function Version: Determining Effective APY

In case you're more into functions:


function effective_apy_midpoint = effective_APY_midpoint(P,Y,n)

% Determines the effective annual yield (APY) given a principal amount, 
% a final amount, and 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;
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
effective_apy_midpoint = current_guess;

No comments: