Bisection Search in Python - Find lowest payment over one year -


i've been going nuts problem hours, , i've been redoing on , over! @ point think i'm seeing numbers flying around me.

anyway, i'm supposed write program finds correct amount of money pay each month on 1 year, pay off debt on credit card. program, there's few conditions must met.

  • it must done using bisection search ((low + high) / 2)
  • there's set balance
  • there's annual interest rate.

here's code @ moment, , i'm getting infinite loops. doing wrong here?

balance = 320000 annualinterestrate = 0.2  monthly_interest = float(annualinterestrate) / 12.0 lower_bound = float(balance / 12) upper_bound = (balance * (1 + monthly_interest)**12) / 12.0 epsilon = 0.01 ans = float(lower_bound + upper_bound) / 2  while abs((balance * (1 + monthly_interest)**12) / 12.0) >= epsilon:      ans = float(lower_bound + upper_bound) / 2     total = float(ans * 12)     new_balance = 0     interest = 0      month in range(0, 12):         interest += ans + (1 + monthly_interest)         new_balance += ans + interest      if new_balance > balance:         upper_bound = ans         print "low" + str(new_balance)     elif new_balance < balance:         lower_bound = ans         print "high" + str(new_balance)     else:         print "what's going on here?"  print "lowest payment: %r" % ans 

i believe there couple things wrong here, first things first, while infinite loop because condition using never converge solution (the variable values never change inside loop). on top of condition (of while) seems wrong kind of problem.

this think trying do, trying find upper , lower bounds "the monthly payment" , convergence condition difference between bounds should less constant epsilon (in other words error should less epsilon).

inside loop calculating midpoint correctly, midpoint taking account interest calculating again. conditions change upper , lower bound not taking account interest part of code little messy.

so, modifying conditions program converges solution:

balance = 320000 annualinterestrate = 0.2  monthly_interest = float(annualinterestrate) / 12.0 lower_bound = float(balance / 12) upper_bound = (balance * (2 + monthly_interest)**12) / 12.0 epsilon = 0.001 ans = float(lower_bound + upper_bound) / 2 total_debt=balance * (1 + annualinterestrate) print total_debt while (upper_bound - lower_bound) >= epsilon:      ans = float(lower_bound + upper_bound) / 2     total = float(ans * 12)      if total > total_debt:         upper_bound = ans         print "low " + str(total)     elif total < total_debt:         lower_bound = ans         print "high " + str(total)     else:         print "solution found"     break   print "lowest payment: %r" % ans 

hope helps!


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

android - Associate same looper with different threads -

visual studio 2010 - Connect to informix database windows form application -