PS4 » Problem 4
def findMaxExpenses(salary, save, preRetireGrowthRates, postRetireGrowthRates,
epsilon):
assert salary > 0, 'Salary must be greater than 0:' + str(salary)
assert 0 < save < 100, 'Savings percentage must be between 0 and 100:' + str(savePct)
assert 0 < epsilon < 1 , 'Upper boundary must be between 0 and 1:' + str(epsilon)
# Generate the savings record.
savingsRecord = nestEggVariable(salary, save, preRetireGrowthRates)
# Savings at retirement will be the last entry;
# it is also the upper limit on possible expenses.
savingsAtRetirement = savingsRecord[-1]
high = savingsAtRetirement
guess = high # Seed initial guess.
low = 0.0 # Seed lower guessing limit.
found = False # Initialize search check.
count = 1 # Initialize a counter, so search doesn't get out of hand.
# Upper limit on count protects against process overruns.
while not found and count < 100:
# Calculate the fund balance with the current guess.
fundBalances = postRetirement(savingsAtRetirement, postRetireGrowthRates, guess)
endingBalance = fundBalances[-1] # Obtain the ending balance for testing.
# Check to see if it is within episilon on either side of 0.
if abs(endingBalance) < epsilon:
found = True
else:
# If not, check to see if it's too high or too low.
if endingBalance < 0:
# Guess was too high. I need a new guess halfway between
# the old one and the low.
high = guess
guess = (low + high)/2
else:
# Guess was too low. I need a new guess halfway between
# the old guess and the last high.
low = guess
guess = (low + high)/2
count = count + 1
return guess