gpt4 book ai didi

python - 仅当解为负时才进行搜索(MIT6.00)

转载 作者:行者123 更新时间:2023-12-01 05:08:56 32 4
gpt4 key购买 nike

各位,

我对 MIT6.00 中 PS1 的问题 3 感到很困惑。我编写了几个函数(一个二分搜索和一个对信用卡债务进行建模的函数)。问题在于,它收敛于一个给出稍微正的剩余信用卡余额的解决方案。我可以降低二分搜索的容差,但我想知道是否有一些更优雅的方法使这个优化器仅返回负结果。

干杯,

艾登

代码:

import numpy as np

def bisection(a, b, fun, tol, var = None):
"""Note that this only works if you put the independant variable
as the first argument in the parameter """
#def tstr(x):
# return 2*(x**2) - 3*x + 1
#sol = bisection(0,0.9,tstr,0.1)

c = (a+b)/2.0

if var != None:
arga = var[:]
argc = var[:]
arga.insert(0,a)
argc.insert(0,c)
else:
arga = a
argc = c

if (b-a)/2.0 <= tol:
#Debugging print statement 1:
#print 'SOL1: c = ', c
if var != None:
return [c] + fun(argc)
else:
return c

if fun(argc)[0] == 0:
if var != None:
return [c] + fun(argc)
else:
return c
elif fun(arga)[0]*fun(argc)[0] < 0:
b = c
else:
a = c
return bisection(a, b, fun, tol, var)


"""
Now we have defined a version of the paidOff function to work
with the bisection method"""

def paidOffBis(args):#(Pay, Bal, Apr):
"""Tester for Bisection Implementation"""
# TEST SIZE OF args:
if (type(args) != list)|(np.size(args) != 3):
print 'Incorrect size or type of input, input size:', np.size(args), '-', args
return None
Pay, Bal, Apr = args
Mpr = Apr/12.0
Baln = Bal
Nm = 0
for n in range(12):
Baln = Baln*(1 + Mpr) - Pay
if (Baln < 0)&(Nm == 0):
Nm = n + 1
if Baln < 0:
return [Baln, Nm]
else:
return [Baln, Nm]

Out_Bal = float(raw_input('Enter the outstanding balance on your credit card: '))
Apr = float(raw_input('Enter the annual credit card interest rate as a decimal: '))

varin = [Out_Bal, Apr]

#(Out_Bal*(1 + (Apr/12.0))**12.0)/12.0
sol = bisection(Out_Bal/12.0, Out_Bal, paidOffBis, 0.01, varin)

print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: $%.2f' % sol[0]
print 'Number of months needed:', sol[2]
print 'Balance: $%.2f' % sol[1]

最佳答案

为了确保余额小于或等于零,您需要正确设置条件语句 - 您需要继续搜索,直到满足该条件。您要求...更优雅的方式...。使用变量的描述性名称并保持简单肯定会改进您的代码。这是使用二分搜索来制定解决方案的一种方法。

annualInterestRate = .1
balance = 1000

def balance_after_one_year(balance, annualInterestRate, payment):
'''Calculate the balance after one year of interest and payments.

balance --> int or float
annualInterestRate --> float between 0 and 1
payment --> float

returns float
'''
for _ in xrange(12):
balance = (balance - payment) * (1 + annualInterestRate / 12.0)
return balance

def min_payment(balance, annualInterestRate, tolerance = .01):
'''Find the minimum payment to pay off a loan.

Uses a bisection search.
Ensures balance is not positive.

balance --> float, int
annualInterestRate --> float less than one
tolerance --> float
'''

# we want the tolerance to be negative
# this isn't strictly a tolerance, it is a lower limit
tolerance = -abs(tolerance)

hi = balance
lo = 0
while True:
payment = (hi + lo) / 2.0
tmp_balance = balance_after_one_year(balance, annualInterestRate, payment)
if tmp_balance < tolerance:
hi = payment
# ensure balance is not positive
elif tmp_balance > 0:
lo = payment
else:
return payment, tmp_balance

用法:

min_pmt, final_balance = min_payment(balance, annualInterestRate)
print 'minimum payment', min_pmt
print 'final balance', final_balance

关于python - 仅当解为负时才进行搜索(MIT6.00),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24558302/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com