在 python 中使用二分法搜索计算最低每月付款
Calculate lowest monthly payment using bisection search in python
我目前正在 edx 上学习 MITx 课程,我有一个练习有问题。你能告诉我为什么我会因为这段代码陷入无限循环吗?我想二分搜索循环不能正常工作,但我真的不知道为什么。这是代码:
balance = 5000
annualInterestRate = 0.18
low = balance/12
high = (balance * (1 + annualInterestRate / 12) ** 12) / 12
guess = (low + high)/2
def getBal(guess, balance, annualInterestRate):
mon = 0
while mon < 12:
mon += 1
ub = balance - guess
balance = ub + (annualInterestRate/12) * ub
return balance
z = getBal(guess, balance, annualInterestRate)
while abs(round(z, 2)) > 0:
if round(z, 2) > 0:
low = guess
else:
high= guess
guess = (high+low)/2
print "Lowest Payment: " + str(round(guess,2))
问题出在第二个循环上。
你可以尝试这样做:
balance = 5000
annual_interest_rate = 0.18
low = balance/12
high = (balance * (1 + annual_interest_rate / 12) ** 12) / 12
guess = (low + high)/2
def get_bal(g, b, air):
mon = 0
while mon < 12:
mon += 1
ub = b - g
b = ub + (air/12) * ub
return b
while True:
z = get_bal(guess, balance, annual_interest_rate)
if abs(round(z, 2)) == 0:
break
if round(z, 2) > 0:
low = guess
else:
high = guess
guess = (high+low)/2
print "Lowest Payment: " + str(round(guess, 2))
我目前正在 edx 上学习 MITx 课程,我有一个练习有问题。你能告诉我为什么我会因为这段代码陷入无限循环吗?我想二分搜索循环不能正常工作,但我真的不知道为什么。这是代码:
balance = 5000
annualInterestRate = 0.18
low = balance/12
high = (balance * (1 + annualInterestRate / 12) ** 12) / 12
guess = (low + high)/2
def getBal(guess, balance, annualInterestRate):
mon = 0
while mon < 12:
mon += 1
ub = balance - guess
balance = ub + (annualInterestRate/12) * ub
return balance
z = getBal(guess, balance, annualInterestRate)
while abs(round(z, 2)) > 0:
if round(z, 2) > 0:
low = guess
else:
high= guess
guess = (high+low)/2
print "Lowest Payment: " + str(round(guess,2))
问题出在第二个循环上。 你可以尝试这样做:
balance = 5000
annual_interest_rate = 0.18
low = balance/12
high = (balance * (1 + annual_interest_rate / 12) ** 12) / 12
guess = (low + high)/2
def get_bal(g, b, air):
mon = 0
while mon < 12:
mon += 1
ub = b - g
b = ub + (air/12) * ub
return b
while True:
z = get_bal(guess, balance, annual_interest_rate)
if abs(round(z, 2)) == 0:
break
if round(z, 2) > 0:
low = guess
else:
high = guess
guess = (high+low)/2
print "Lowest Payment: " + str(round(guess, 2))