鱼C论坛

 找回密码
 立即注册
查看: 2030|回复: 2

关于一个迭代的问题

[复制链接]
发表于 2015-4-11 13:18:48 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 zetro 于 2015-4-11 13:25 编辑

新人第一帖,没有多少金币,就不散了(主要是没有找到在哪可以悬赏的)。望大神关注。
问题是这样的算一个关于利息和花钱的作业,每年的利息是是用一个list表示出来的
迭代公式是这样的:F[n]=F[n-1]*(1+0.01*growthRates[n])-expenses
但是我算出来的答案是这样的:[80000.00000000001, 54000.000000000015, 20000.000000000015, -1964.9999999999818, -38563.70919999998]
正确答案是:[80000.000000000015, 54000.000000000015, 24000.000000000015, -4799.9999999999854, -34847.999999999985]
检查出来的错误应该是出现在retireFound()部分,但是不明白是哪里出现了问题。求大神们指点一二
另外,问什么小数点后面会出现这么0.000000000015这种数据,感觉是因为计算机把浮点数转换为二进制的时候出现的问题,不知道这种解释对不对?还有个问题,怎么添加代码文字,还要有行标记的那种呢
以下是代码:

def retireFund(first,bito,n,expenses):
    a=1+0.01*bito
    print (bito)
    b=first
    i=n
    if i==0:
        return b
    else:
        return retireFund(first,bito,i-1,expenses)*a-expenses

def postRetirement(saving, growthRate,expenses):
    """
    - salary: the amount of money you make each year.
    - save: the percent of your salary to save in the investment account each
      year (an integer between 0 and 100).
    - growthRate: the annual percent increase in your investment account (an
      integer between 0 and 100).
    - years: the number of years to work.
    - return: a list whose values are the size of your retirement account at
      the end of each year.
    """
    F=[]
    n=0
    years=len(growthRate)
    first=saving*(1+0.01*growthRate[0])-expenses
    while n<years:
        bito=growthRate[n]      
        F.append(retireFund(first,bito,n,expenses))
        n=n+1
    return F

def testPostRetirement():
    savings     = 100000
    growthRates = [10, 5, 0, 5, 1]
    expenses    = 30000
    savingsRecord = postRetirement(savings, growthRates, expenses)
    print (savingsRecord)
    # Output should have values close to:
    # [80000.000000000015, 54000.000000000015, 24000.000000000015,
    # -4799.9999999999854, -34847.999999999985]
    # TODO: Add more test cases here.    # TODO: Add more test cases here.


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2015-4-11 19:09:48 | 显示全部楼层
python里面没有double和float之分,默认的带小数点的出发和乘法都用float变量,而这个float变量的精度是17位,也就是说超过17位的数字是没有意义的,如果要处理高精度的处理,需要第三方模块的支持,可以搜索python高精度,应该会有相应的介绍文章,个人见解,楼主试一下吧
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2015-4-14 05:59:12 | 显示全部楼层
看一下
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-2-15 14:57

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表