gpt4 book ai didi

python - Python错误 “ZeroDivisionError: float division by zero”

转载 作者:行者123 更新时间:2023-12-03 08:43:01 25 4
gpt4 key购买 nike

执行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)示例:

  • 不管满足什么条件,rate_high都会持续降低,因为每个循环都以速率除以2开始。
  • pv_test高于pv,然后在速率如此低(test_pv = pmt *(1-(1 + r)**(-n))/r)时转换为零,因为提名者的下降速度快于分母。
  • 之后,速率以零test_pv继续降低,速率甚至更快(rate_high =(rate_high + rate_low)/2)。
  • 该速率最终达到5e-324,并且进一步降低后,几乎变为零,导致(pmt *(1-(1 + r)**(-n))/ r )被零除。

  • 建议的解决方案:
    更改付款方式(pv_annuity(rate,n, pmt )),它应反射(reflect)出费用的变化。

    关于python - Python错误 “ZeroDivisionError: float division by zero”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59978285/

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