Last active
October 26, 2021 03:16
-
-
Save themichaelyang/c45d8de4cf125b7391adfd49c361a5ec to your computer and use it in GitHub Desktop.
MIT 6.0001 Problem Set 1C Solutions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# MIT OCW 6.0001 | |
# PSET 1C | |
# SOLUTION | |
# salary | |
starting_annual_salary = int(input("Starting salary? ")) | |
# starting_annual_salary = 10000 | |
semi_annual_raise = 0.07 | |
# investments | |
annual_rate = 0.04 | |
monthly_rate = annual_rate / 12 | |
# target savings | |
down_payment_percentage = 0.25 | |
house_price = 10**6 | |
target_savings = house_price * down_payment_percentage | |
# how close is acceptable? | |
acceptable_diff = 100 | |
# bisection | |
upper_bound = 1.0 | |
lower_bound = 0.0 | |
steps = 0 | |
diff_from_target = target_savings * 2 # initialize to anything much larger than target savings | |
percentage_saved = 0.5 | |
# while not yet in acceptable range | |
while abs(diff_from_target) > acceptable_diff and steps < 100: | |
percentage_saved = (upper_bound + lower_bound) / 2 | |
annual_salary = starting_annual_salary | |
current_savings = 0 | |
months_passed = 0 | |
# figure out savings over 36 months | |
while months_passed < 36: | |
monthly_salary = annual_salary / 12 | |
current_savings += current_savings * monthly_rate | |
current_savings += percentage_saved * monthly_salary | |
months_passed += 1 | |
# raise salary every 6 months | |
if months_passed % 6 == 0: | |
annual_salary += annual_salary * semi_annual_raise | |
diff_from_target = target_savings - current_savings | |
# saved too little! | |
if diff_from_target > 0: | |
lower_bound = percentage_saved | |
# saved too much! | |
elif diff_from_target < 0: | |
upper_bound = percentage_saved | |
steps += 1 | |
else: # this "else" is for the while loop when it exits (look this up) | |
if abs(diff_from_target) <= acceptable_diff: | |
# {0:.4f} means replace with the argument at index 0 and round to 4 digits (:.4f) | |
# {1} means replace with the argument at index 1 | |
print("%: {0:.4f}, steps: {1}".format(percentage_saved, steps)) | |
else: | |
print("Not possible! :~(") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment