Python 用于计算住房存款所需的储蓄月数的函数

Python 用于计算住房存款所需的储蓄月数的函数,python,function,math,finance,Python,Function,Math,Finance,完全公开这是一项任务,但我的输出与给定测试用例的任务之间存在一些差异 该函数计算您的年薪、每月节省的工资的百分比以及房屋成本 假设我需要房子总成本的25%。每个月我工资的一部分用于储蓄,我的储蓄每月还可获得4%的利息 def house_hunting(annual_salary, portion_saved, total_cost): portion_down_payment = 0.25 * total_cost current_savings = 0 r = 0.

完全公开这是一项任务,但我的输出与给定测试用例的任务之间存在一些差异

该函数计算您的年薪、每月节省的工资的百分比以及房屋成本


假设我需要房子总成本的25%。每个月我工资的一部分用于储蓄,我的储蓄每月还可获得4%的利息

def house_hunting(annual_salary, portion_saved, total_cost):

    portion_down_payment = 0.25 * total_cost
    current_savings = 0
    r = 0.04
    months = 0

    while current_savings < portion_down_payment:
        current_savings += (annual_salary * portion_saved) / 12
        current_savings += current_savings * r / 12
        months += 1

    return months

print( house_hunting(120000,0.1,1000000) )
print( house_hunting(80000,0.15,500000) )
def house_hunting(年薪、节省部分、总成本):
部分首付=0.25*总成本
当前储蓄=0
r=0.04
月份=0
当活期存款<部分首付时:
当前储蓄+=(年薪*部分储蓄)/12
活期存款+=活期存款*r/12
月份+=1
返回月份
印刷品(房屋狩猎(120000,0.11000000))
印刷品(房屋狩猎(80000,0.15500000))
第一个电话给了我182个月,测试用例显示183个月。 第二次调用给了我105个月,根据测试用例,这是正确的


所以我的数学在某个地方出错了;有人知道我错在哪里了吗?

问题是你给每一笔新存款一个月的利息。相反,你必须等到下个月。因此,对于每个月,您应该计算整个月持有的余额的利息,然后进行新的存款。非常简单,切换这两条线路:

while current_savings < portion_down_payment:
    current_savings += current_savings * r / 12
    current_savings += (annual_salary * portion_saved) / 12
    months += 1
当活期存款

现在您得到了正确的结果。

只需修改顺序,如下所示:

while current_savings < portion_down_payment:
    current_savings += current_savings * r / 12
    current_savings += (annual_salary * portion_saved) / 12
当活期存款

你的储蓄(上个月的活期储蓄)会得到利息,然后再加上新的收入。

“我的储蓄每月也能获得4%的利息”-这是一个荒谬的利率,也不是你所实施的利率。如果1=100%,那么0.04=4%,你实施了4%的名义年利率,每月复利,不是每月4%的利息。我不做金融。按照作业要求去做。这不是财务;它对公式的理解足以完成作业。