作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在尝试解决这个 MIT OCW assignment 上的第三个问题.它要求您使用二等分搜索方法计算一年内清算给定债务所需的每月付款。我得到了预期的输出类型,但结果非常不准确。有人可以指出我哪里出错了吗?谢谢
# Problem Set 1("C")
# Time Spent: xx hours
def payInOne_BisectionSearch (balance,annualRate):
#initialize variables
initialBalance = balance
monthlyRate = float(annualRate/12.0)
minMonthly = float(balance/12.0)
maxMonthly = float((balance * (1 + monthlyRate ** 12.0 ))/12.0)
monthlyPayment = float((minMonthly + maxMonthly)/2)
numMonths = 1
#define function to check balance after 12 months
def balanceAfterYear (balance, monthlyRate, monthlyPayment):
for numMonths in range (1,13):
interest = balance * monthlyRate
balance += interest - monthlyPayment
if balance <= 0:
break
return [balance, numMonths]
while maxMonthly - minMonthly >= .005:
balance = initialBalance
monthlyPayment = float((minMonthly + maxMonthly)/2)
if balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] < 0:#paying too much
maxMonthly = monthlyPayment
elif balanceAfterYear(balance,monthlyRate,monthlyPayment)[0] > 0:#paying too little
minMonthly = monthlyPayment
else:
break
print "Monthly payment to pay off debt in 1 year:", round(monthlyPayment,2)
print "Number of months needed:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[1], 2)
print "Balance:", round(balanceAfterYear(balance,monthlyRate,monthlyPayment)[0], 2)
payInOne_BisectionSearch (float(raw_input("Enter the outstanding balance")),float(raw_input("Enter annual rate as a decimal")))
'''Test Case Expected:
Enter the outstanding balance on your credit card: 320000
Enter the annual credit card interest rate as a decimal: .2
RESULT
Monthly payment to pay off debt in 1 year: 29643.05
Number of months needed: 12
Balance: -0.1
Test Case Actual Output:
Enter the outstanding balance320000
Enter annual rate as a decimal.2
Monthly payment to pay off debt in 1 year: 26666.67
Number of months needed: 12.0
Balance: 39179.43'''
最佳答案
您的问题在于您的初始 maxMonthly 值。我想你真正想要的是将它定义为
maxMonthly = float((balance * ((1 + monthlyRate) ** 12.0 ))/12.0)
否则 monthlyRate**12
的计算结果将接近于零(对于介于 0 和 1 之间的 monthlyRate
),这将使 maxMonthly 的计算结果为 balance/12.0
与您的 minMonthly
相同,这将使最后的 while 循环永远不会开始。
关于algorithm - Python二分搜索逻辑错误-返回不准确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40820550/
我正在尝试编写一个程序,在名为 items 的数组中进行顺序搜索和二分搜索,该数组具有 10000 个已排序的随机 int 值。第二个名为 targets 的数组加载了 1000 个 int 值(50
当我尝试使用图表并为其编写一些代码但没有成功时,我遇到了一个问题:/!! 我想创建一些东西来获取图形数据并检查它是否:1- 连接2-二分法3-有循环4-是一棵树 所以我想知道,例如,是否可以将其写入以
我是一名优秀的程序员,十分优秀!