MIT OCW 6.0001 课程 Problem Set 1 作业(Part C)

MIT OCW 6.0001 课程 Problem Set 1 作业(Part C)

打卡记录

打卡时间:2019.07.27-2019.07.29
打卡天数:D04
学习内容:MIT OCW 6.0001 课程 Problem Set 1 作业(Part C)

参考链接

课程视频
作业链接

Part C 作业:

Part C: Finding the right amount to save away

In Part B, you had a chance to explore how both the percentage of your salary that you save each month and your annual raise affect how long it takes you to save for a down payment. This is nice, but suppose you want to set a particular goal, e.g. to be able to afford the down payment in three years. How much should you save each month to achieve this? In this problem, you are going to write a program to answer that question. To simplify things, assume:

  1. Your semi­annual raise is .07 (7%)
  2. Your investments have an annual return of 0.04 (4%)
  3. The down payment is 0.25 (25%) of the cost of the house
  4. The cost of the house that you are saving for is $1M.

You are now going to try to find the best rate of savings to achieve a down payment on a 1M house in 36 months. Since hitting this exactly is a challenge, we simply want your savings to be within100 of the required down payment.

In ps1c.py, write a program to calculate the best savings rate, as a function of your starting salary. You should use bisection search to help you do this efficiently. You should keep track of the number of steps it takes your bisections search to finish. You should be able to reuse some of the code you wrote for part B in this problem.

Because we are searching for a value that is in principle a float, we are going to limit ourselves to two decimals of accuracy (i.e., we may want to save at 7.04% ­­ or 0.0704 in decimal – but we are not going to worry about the difference between 7.041% and 7.039%). This means we can search for an integer between 0 and 10000 (using integer division), and then convert it to a decimal percentage (using float division) to use when we are calculating the current_savings after 36 months. By using this range, there are only a finite number of numbers that we are searching over, as opposed to the infinite number of decimals between 0 and 1. This range will help prevent infinite loops. The reason we use 0 to 10000 is to account for two additional decimal places in the range 0% to 100%. Your code should print out a decimal (e.g. 0.0704 for 7.04%).

Try different inputs for your starting salary, and see how the percentage you need to save changes to reach your desired down payment. Also keep in mind it may not be possible for to save a down payment in a year and a half for some salaries. In this case your function should notify the user that it is not possible to save for the down payment in 36 months with a print statement. Please make your program print results in the format shown in the test cases below.

Note: There are multiple right ways to implement bisection search/number of steps so your results may not perfectly match those of the test case.

作业心得

PartC的作业,根据以下前提条件,计算如果3年内要付首付,每月最优存款比例:

  1. 年薪涨幅是 .07 (7%)
  2. 投资年回报率是 0.04 (4%)
  3. 首付是总款的0.25(25%)
  4. 总款是1百万

有几点需要注意:

  • 需要用到 bisection search 算法
  • 每月存款比例保留小数点后两位,比如7.041%,使用浮点数表示为 0.0741,所以我们可以利用0-10000的整数来做算法计算,最后再转化为float

本次作业学习到以下知识点:

程序逻辑引入了全局变量,显得不太优雅,仍有改善空间。

程序实现的时候,参考了一下连接:
https://github.com/iamwhil/6.0001(运行结果与作业中的测试相符)
https://github.com/kaizenflow/6.0001-ps1(无法得到正确的结果)

程序代码

# 起始年薪
annual_salary = 1500000
# annual_salary = float(input("Enter the starting salary:"))

# 房价
total_cost = 1000000

# 薪资涨幅
semi_annual_raise = 0.07
# 首付比例
portion_down_payment = 0.25
# 存款年化率
R = 0.04

deep = 0

# 首付
down_payment = total_cost * portion_down_payment

last_portion_saved = False

def month_counter(current_savings, annual_salary, portion_saved):
    # 当前月份
    month_count = 1
    # while loop
    while True:
        # 当月情况判断
        # 计算当月存款 = 存款 + 月薪*每月薪资存款比例 + 投资回报
        current_savings = current_savings + annual_salary/12*portion_saved + current_savings*R/12

        # 如果存款 和 首付,相差不到100,也算达成条件
        if current_savings >= down_payment:
            break
        
        if month_count % 6 == 0:
            annual_salary += annual_salary * semi_annual_raise

        # 月份自增
        month_count += 1

    return [month_count, current_savings]

def bisection_search(portion_saved_rates, annual_salary):
    global last_portion_saved
    global deep
    deep += 1

    # 计算中位数,【//】 符合表示除法的商是整数
    if len(portion_saved_rates) == 1:
        return last_portion_saved


    middle = len(portion_saved_rates) // 2
    portion_saved = portion_saved_rates[middle] / 10000

    init_current_savings = 0

    # 如何计算的月份与预期相等
    res = month_counter(init_current_savings, annual_salary, portion_saved)
    month_count = res[0]
    current_savings = res[1]

    # print(portion_saved_rates, month_count, current_savings, portion_saved, abs(current_savings - down_payment))

    if month_count == month_count_expect:
        last_portion_saved = portion_saved_rates[middle]
        if abs(current_savings - down_payment) > 100:
            return bisection_search(portion_saved_rates[:middle], annual_salary)
        else:
            return portion_saved_rates[middle]
    elif month_count > month_count_expect:
        # 计算的月份比期望的大,说明存款比例少了,要提升比例
        # print(portion_saved_rates[:middle])
        return bisection_search(portion_saved_rates[middle:], annual_salary)
    else:
        return bisection_search(portion_saved_rates[:middle], annual_salary)

portion_saved_rates = range(0, 10000)
month_count_expect = 36

res = bisection_search(portion_saved_rates, annual_salary)
if res is False:
    print("It is not possible to pay the down payment in three years.")
else:
    print("Best savings rate: {}".format(res/10000))
    print(res/10000) 
    print("Steps in bisection search: {}".format(deep)) 
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 203,271评论 5 476
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,275评论 2 380
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,151评论 0 336
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,550评论 1 273
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,553评论 5 365
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,559评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,924评论 3 395
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,580评论 0 257
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,826评论 1 297
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,578评论 2 320
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,661评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,363评论 4 318
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,940评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,926评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,156评论 1 259
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,872评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,391评论 2 342

推荐阅读更多精彩内容