python - 构建函数 saving_calculator(PMT, n, i )` that calculates your customer' s 退休时的储蓄

标签 python python-3.x

我正在开发一个项目,我必须编写一段代码来计算客户退休时的储蓄:

def savings_calculator(PMT, n, i):
    FV = 0
    for j in range(n):
        interest = FV * i
        FV = FV + interest
        FV = FV + PMT
        FV = round(FV,2)
    return FV

问题是一旦我对 FV 进行四舍五入,我有时会得到错误的值

下面的测试用例应该返回 true:

savings_calculator(20000, 15, 0.1) == 635449.63 True

savings_calculator(10000, 20, 0.1) == 572749.99 返回 false,因为四舍五入返回错误的值

最佳答案

如果您不在每次迭代时进行舍入,而只在最后进行舍入,您应该得到正确的答案:

def savings_calculator(PMT, n, i):
    FV = 0 
    for j in range(n):
        interest = FV * i 
        FV = FV + interest 
        FV = FV + PMT

    FV = round(FV,2)

    return FV

舍入本质上是通过降低精度引入了小误差。经过多次迭代后,此错误会累积起来,因此应仅在最后进行舍入。

关于python - 构建函数 saving_calculator(PMT, n, i )` that calculates your customer' s 退休时的储蓄,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52820251/

相关文章:

python - 根据 py.test 中的参数跳过测试

python - urllib.parse vs urlparse : How do I get python 2. 7 识别urllib?

python - 装饰类的继承类方法中的 cls 行为

python - 如何在cython中编译多个文件

python - 如何使用数据类装饰pyqt5类?

python - python 中嵌套循环中的嵌套打印

python - 我如何实现具有多个 init 继承的 super() ?

python-3.x - 如何让TQDM进度条在KB和MB之间自动更新

python - SQLite在使用executemany时获取id并插入

python - 如何在特定日期从 github pip 安装