t********n 发帖数: 611 | 1 自学编程遇到困难,哪位前辈帮忙看看:
问题是:要求写一个程序,计算如果每月还固定金额,一年把信用卡债务还清,每月需
要支付多少钱,前提是这一年都不再使用信用卡借债。要求用bisection
lower bound= outstanding balance/12
upper bound=( outstanding balance (1+monthly interest rate)**12)/12
以下是问题link:
http://ocw.mit.edu/courses/electrical-engineering-and-computer-
第3题不会做,我写的程序是这样的:
initialBalance= float (raw_input ('Enter the outstanding balance:'))
annualInterest= float (raw_input('Enter the annula interest rate'))
monthlyInterest= annualInterest/12.0
lower= initialBalance/12.0
upper= initialBalance*((1+monthlyInterest)**12)/12.0
balance=initialBalance
while upper-lower>0.005:
monthPay=(lower+upper)/2.0
print 'current monthly payment:', monthPay
for month in range (1,13):
interest= balance*monthlyInterest
balance= balance+interest- monthPay
print 'balance at the end of month',month
print balance
if balance>0:
lower=monthPay
else:
upper= monthPay
balance= round (balance, 2)
print 'RESULT:'
print "the amount to pay each month:", monthPay
print 'the months you need:', month
print 'Balance at the end of the year:', balance
网上的标准答案是这样的:
# Use bisection search until the search space is sufficiently small
while True:
balance = original_balance
monthly_payment = (low_payment + high_payment)/2
# Simulate passage of time until outstanding balance is paid off
# Each iteration represents 1 month
for month in range(1,13):
interest = round(balance*interest_rate/12, 2)
balance += interest - monthly_payment
if balance <= 0:
break
if (high_payment - low_payment < 0.005):
# Bisection search space is small enough
# Print result
print "RESULT"
# Round monthly payment up to the nearest cent
monthly_payment = round(monthly_payment + 0.004999, 2)
print "Monthly payment to pay off debt in 1 year:", round(monthly_
payment,2)
# Recompute remaining balance and the number of months needed
balance = original_balance
for month in range(1,13):
interest = round(balance*interest_rate/12, 2)
balance += interest - monthly_payment
if balance <= 0:
break
print "Number of months needed:", month
print "Balance:", round(balance,2)
break
elif balance < 0:
#Paying too much
high_payment = monthly_payment
else:
#Paying too little
low_payment = monthly_payment
用的语言是 python, operating system is mac os x 10.8.2
Thanks a lot!!! | f**f 发帖数: 30 | 2 你写的貌似有indentation错误
for 循环算出balence就完成任务了,接下来那个改变lower和upper应该在for循环的外
边,while循环的里边? | t********n 发帖数: 611 | 3 谢谢!! 我按你说的试试一下!!
【在 f**f 的大作中提到】 : 你写的貌似有indentation错误 : for 循环算出balence就完成任务了,接下来那个改变lower和upper应该在for循环的外 : 边,while循环的里边?
|
|