问题
Following is the problem set from MIT opencourseware
Part C: Finding the right amount to save away
- Your semiannual raise is .07 (7%)
- Your investments have an annual return of 0.04 (4%)
- The down payment is 0.25 (25%) of the cost of the house
- The cost of the house that you are saving for is $1M.
I am now going to try to find the best rate of savings to achieve a down payment on a $1M house in 36 months. And I want your savings to be within $100 of the required down payment.I am stuck with the bisection search and 'It is not possible to pay the down payment in three years.' this output. I am new to programmers and English.Any help is appreciated.
And here is my code:
starting_salary = float(input("Enter your starting salary: "))
months_salary = starting_salary/12
total_cost = 1000000.0
semi_annual_rate = .07
investment_return = 0.04
down_payment = total_cost * 0.25
r = 0.04
current_savings = 0.0
#months = 36
tolerance = 100
steps = 0
high = 1.0
low = 0.0
guess = (high+low)/2.0
total_salaries = 0.0
def calSavings(current_savings,months_salary,guess,month):
for months in range(0,37):
if months%6==1 and months >1:
months_salary=months_salary*(1+semi_annual_rate)
current_savings = current_savings + months_salary * guess
current_savings = current_savings * (1+0.04/12)
return(current_savings)
current_savings = calSavings(current_savings,months_salary,guess,1)
while abs(current_savings-down_payment)>=100:
if current_savings < down_payment:
low = guess
elif current_savings > down_payment:
high = guess
else:
print("It is not possible to pay the down payment in three years.")
break
guess = (low+high)/2
steps = steps +1
print("Best saving rate: ", guess)
When I run this code, it will be stuck. I don't know why. And I don't know how to determine which is the condition of output this "It is not possible to pay the down payment in three years."
I have seen Similar questions on stackoverflow like this and this but I am not quite followed.
回答1:
I've already addressed most of my points in the comments, but I will recap: You are trying to solve a problem using a method called recursive solving, in this case using the bisection method.
The steps are as follows:
- start with an initial
guessyou chose0.5 - Perform your calculations in a loop and iterate the initial guess, in this case you must account for the following:
- Maximum number of steps before failure, remember we can always add 2 values and divide by 2, your result will tend to 0.999999.. otherwise
- A certain tolerance, if your step size is not small enough 25% of 1 M is 250 000 and you might never hit that number exactly, that' why you make a tolerance interval, for example: anything between 250 000 and 251 000 --> break loop, show result.
- Your if statements for changing
lowandhighto adjust guess are correct, but you forget to re-initialize savings to 0 which means savings was going to infinity.
Now that's all said, here's a working version of your code:
starting_salary = 100000 # Assuming Annual Salary of 100k
months_salary = starting_salary/12
total_cost = 1000000.0
semi_annual_rate = .07
investment_return = 0.04
down_payment = total_cost * 0.25
print("down payment: ", down_payment)
r = 0.04
current_savings = 0.0
#months = 36
tolerance = 100
steps = 0
high = 1.0
low = 0.0
guess = (high+low)/2.0
total_salaries = 0.0
tolerance = down_payment/100 # I chose this tolerance to say if my savings are between [down_payment - (downpayment + down_payment/100)] result is admissible. (this is quite a high tolerance but you can change at leisure)
def calSavings(current_savings,months_salary,guess,month):
for months in range(0,37):
if months%6==1 and months >1:
months_salary=months_salary*(1+semi_annual_rate)
current_savings = current_savings + months_salary * guess
current_savings = current_savings * (1+0.04)
return(current_savings)
while abs(current_savings-down_payment)>=100:
current_savings = calSavings(current_savings,months_salary,guess,1)
if current_savings < down_payment:
low = guess
current_savings = 0.
elif current_savings > down_payment + tolerance:
high = guess
current_savings = 0.
if (steps > 100): # I chose a maximum step number of 100 because my tolerance is high
print("It is not possible to pay the down payment in three years.")
break
guess = (low+high)/2
steps = steps +1
print("Best saving rate: ", guess)
print("With current savings: ", current_savings)
Output:
down payment: 250000.0
Best saving rate: 0.656982421875
With current savings: 250072.3339667072
[Finished in 0.08s]
回答2:
# user input
annual_salary = float(input('Enter your annual salary: '))
semi_annual_raise = 0.07
r = 0.04
portion_down_payment = 0.25
total_cost = 1000000
steps = 0
current_savings = 0
low = 0
high = 10000
guess_rate = (high + low)//2
# Use a while loop since we check UNTIL something happens.
while abs(current_savings - total_cost*portion_down_payment) >= 100:
# Reset current_savings at the beginning of the loop
current_savings = 0
# Create a new variable for use within the for loop.
for_annual_salary = annual_salary
# convert guess_rate into a float
rate = guess_rate/10000
# Since we have a finite number of months, use a for loop to calculate
# amount saved in that time.`enter code here`
for month in range(36):
# With indexing starting a zero, we need to calculate at the beginning
# of the loop.
if month % 6 == 0 and month > 0:
for_annual_salary += for_annual_salary*semi_annual_raise
# Set monthly_salary inside loop where annual_salary is modified
monthly_salary = for_annual_salary/12
# Calculate current savings
current_savings += monthly_salary*rate+current_savings*r/12
# The statement that makes this a bisection search
if current_savings < total_cost*portion_down_payment:
low = guess_rate
else:
high = guess_rate
guess_rate = (high + low)//2
steps += 1
# The max amount of guesses needed is log base 2 of 10000 which is slightly
# above 13. Once it gets to the 14th guess it breaks out of the while loop.
if steps > 13:
break
# output
if steps > 13:
print('It is not possible to pay the down payment in three years.')
else:
print('Best savings rate:', rate)
print('Steps in bisection search:', steps)
回答3:
For answer visit the GitHub link - MIT has added Problem set solutions
Part C: Finding the right amount to save away
In Part B, you had a chance to explore how both the percentage of your salary that you save each month and your annual raise affect how long it takes you to save for a down payment. This is nice, but suppose you want to set a particular goal, e.g. to be able to afford the down payment in three years. How much should you save each month to achieve this? In this problem, you are going to write a program to answer that question. To simplify things, assume:
- Your semiannual raise is .07 (7%)
- Your investments have an annual return of 0.04 (4%)
- The down payment is 0.25 (25%) of the cost of the house
- The cost of the house that you are saving for is $1M.
You are now going to try to find the best rate of savings to achieve a down payment on a $1M house in 36 months. Since hitting this exactly is a challenge, we simply want your savings to be within $100 of the required down payment. In ps1c.py, write a program to calculate the best savings rate, as a function of your starting salary.
You should use bisection search to help you do this efficiently. You should keep track of the number of steps it takes your bisections search to finish. You should be able to reuse some of the code you wrote for part B in this problem.
Because we are searching for a value that is in principle a float, we are going to limit ourselves to two decimals of accuracy (i.e., we may want to save at 7.04% or 0.0704 in decimal – but we are not going to worry about the difference between 7.041% and 7.039%). This means we can search for an integer between 0 and 10000 (using integer division), and then convert it to a decimal percentage (using float division) to use when we are calculating the current_savings after 36 months. By using this range, there are only a finite number of numbers that we are searching over, as opposed to the infinite number of decimals between 0 and 1. This range will help prevent infinite loops. The reason we use 0 to 10000 is to account for two additional decimal places in the range 0% to 100%. Your code should print out a decimal (e.g. 0.0704 for 7.04%).
Try different inputs for your starting salary, and see how the percentage you need to save changes to reach your desired down payment. Also keep in mind it may not be possible for to save a down payment in a year and a half for some salaries. In this case your function should notify the user that it is not possible to save for the down payment in 36 months with a print statement. Please make your program print results in the format shown in the test cases below.
Note: There are multiple right ways to implement bisection search/number of steps so your results may not perfectly match those of the test case.
Hints:
● There may be multiple savings rates that yield a savings amount that is within $100 of the required down payment on a $1M house. In this case, you can just return any of the possible values.
● Depending on your stopping condition and how you compute a trial value for bisection search, your number of steps may vary slightly from the example test cases.
● Watch out for integer division when calculating if a percentage saved is appropriate and when calculating final decimal percentage savings rate.
● Remember to reset the appropriate variable(s) to their initial values for each iteration of bisection search.
来源:https://stackoverflow.com/questions/53374233/mit-programming-in-python-problem-set-1-part-c