[Tutor] Python problem
Vakhtang Kvaratskhelia
va_kvaratskhelia at cu.edu.ge
Sat Feb 20 06:27:01 EST 2021
Hello,
i have written the following code that uses the bisection search to find
the optimal percentage to save.
However i am unable to prevent an infinite loop in case the annual salary
is 10,000
also i do not get how i can use only integer division while using the
bisection search? when i substitute // division instead of / division the
loop runs infinitely.
I want to use this hint : "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%)."
but i am not able to.
this is the code i have written and it gives the correct amount as a
solution except it is not rounded to 4 decimals as it would have been if i
was using integer division:
annual_salary=150000
total_cost=1000000
Months=36
semi_annual_raise=0.07
portion_down_payment=0.25
r=0.04
portion_saved=0
epsilon=100
possible_savings=0
Steps=0
for i in range(0,Months):
possible_savings+= annual_salary/12 + possible_savings*0.04/12
if (i+1)%6 == 0:
annual_salary=annual_salary*(1+semi_annual_raise)
low=0
high=10000
while abs(total_cost*portion_down_payment - portion_saved *
possible_savings) >= epsilon:
if portion_saved * possible_savings < total_cost*portion_down_payment :
low=portion_saved
else:
high=portion_saved
portion_saved=(high+low)/2
Steps+=1
print("Optimal portion saved is = ",portion_saved)
print("Steps in bisection search: ",Steps)
Can you help with this?
Thank you in advance.
More information about the Tutor
mailing list