执行annuity_rate(5, 100, 510)
或尝试使用负值时,我一直收到此错误。我怎样才能解决这个问题?
它适用于较大的数字,但对于负数和较小的数字却不起作用。
def pv_annuity(r, n, pmt):
""" Return the present value of an annuity of pmt to be received
each period for n periods"""
pv = pmt * (1 - (1 + r) ** (-n)) / r
return pv
def annuity_rate(n, pmt, pv):
""" return the rate of interest required to amortize the pv in n periods
with equal periodic payments of pmt"""
rate_low, rate_high = 0, 1
while True:
rate = (rate_high + rate_low) / 2
#print('trying rate', rate)
test_pv = pv_annuity(rate, n, pmt)
#print(test_pv)
if abs(pv - test_pv) <= 0.01:
break
if test_pv > pv:
rate_low = (rate_high + rate_low) / 2
if test_pv < pv:
rate_high = (rate_high + rate_low) / 2
return rate
最佳答案
使用您的annuity_rate(5,100,510)示例:
建议的解决方案:
更改付款方式(pv_annuity(rate,n, pmt )),它应反射(reflect)出费用的变化。