基于对另一个StackExchange网站的一些研究,似乎以下程序应根据我对所提出的计算的理解显示var_a
的原始值。但是,函数a
似乎没有按预期计算a
的值,并且我不清楚为什么会出现这种情况。在尝试正确解决var_a
时应如何解决这个问题?
#! /usr/bin/env python3
import math
def main():
var_n = 35 # thirty-five year investment
var_iy = .04 # four percent interest per year
var_pv = 30000 # thirty thousand dollar investment
var_a = 12 # compounded twelve times per year
var_fv = round(fv(var_n, var_iy, var_pv, var_a), 2)
print('Future Value =', var_fv)
var_a = a(var_n, var_iy, var_pv, var_fv)
print('Compounded Per Year =', var_a)
fv = lambda n, iy, pv, a: pv * (iy / a + 1) ** (n * a)
def a(n, iy, pv, fv):
b = -math.log(fv / pv) / (iy * n)
return (iy * b) / (lambert_w(b * math.exp(b)) - b)
def lambert_w(z, tolerance=1e-8):
a = z
while True:
b = math.exp(a)
c = a * b
d = a - (c - z) / (c + b)
if abs(a - d) <= tolerance:
return a
a = d
if __name__ == '__main__':
main()