python - 如何获得 range() 函数的输出以与我的二分搜索方法进行交互?
问题描述
考虑到某些因素,例如(加薪和年回报率),下面的代码应该计算储蓄率将在 36 个月内还清我的首付。我无法让 range 函数的输出与我的交互二分搜索法。
# Cost
total_cost = 1000000
portion_down_payment = .25 * total_cost
# Salary
annual_salary = 150000
semi_annual_raise = .07
annual_return_rate = .04
current_savings = 0
month = 0
# Bisection
epsilon = 100
num_guesses = 0
low = 0
high = 1
saving_rate = (high + low) / 2.0
portion_saved_monthly = annual_salary / 12 * saving_rate
# range()function
for x in range(36):
current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
month += 1
if month % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
portion_saved_monthly = annual_salary / 12 * saving_rate
while abs(current_savings - portion_down_payment) >= epsilon:
if current_savings < portion_down_payment:
low = saving_rate
else:
high = saving_rate
saving_rate = (high + low) / 2.0
num_guesses += 1
print('Best savings rate: ', saving_rate)
print('Steps in bisection search: ', num_guesses)
解决方案
我从 while 循环开始,将 for 循环嵌套在里面。我还在 while 循环中移动了一些变量,这有助于我得到正确的答案。
'''
# Cost of House
total_cost = 1000000
portion_down_payment = .25 * total_cost
# Salary
annual_salary_input = float(input('Enter the starting salary: '))
current_savings = 0
# Bisection
epsilon = 100
num_guesses = 0
low = 0
high = 1
saving_rate = (high + low) / 2.0
portion_saved_monthly = annual_salary_input / 12 * saving_rate
while abs(current_savings - portion_down_payment) >= epsilon:
annual_salary = annual_salary_input
semi_annual_raise = .07
annual_return_rate = .04
current_savings = 0
month = 0
portion_saved_monthly = annual_salary / 12 * saving_rate
saving_rate = (high + low) / 2.0
# Loop
for x in range(36):
current_savings += (current_savings * annual_return_rate / 12) + portion_saved_monthly
month += 1
if month % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
portion_saved_monthly = annual_salary / 12 * saving_rate
if current_savings < portion_down_payment:
low = saving_rate
else:
high = saving_rate
saving_rate = (high + low) / 2.0
num_guesses += 1
if num_guesses > 1000:
break
if saving_rate < 1.0:
print('Best savings rate: ', "%.4f" % saving_rate)
print('Steps in bisection search: ', num_guesses)
else:
print('It is not possible to pay the down payment in three years.')
'''
推荐阅读
- mysql - 如何准确选择用户名和密码注意大小写字母 - mysql
- python - After using @ray decorator can't add data to dictionary
- mysql - Laravel NULL 日期是有效的“今天”日期
- ios - pod install error [!] 无法添加 URL 名为“master-1”的源
- c# - Session.clear 会话放弃不起作用
- odoo - 如何在 ubuntu 14.04 中安装 odoo?开发 odoo 模块(如 html、css 等)的基本要求是什么
- android - 如何确保 .gitignore 适用于同一存储库中的多个 Android 项目
- java - 以编程方式设置按钮的布局(计算器)
- javascript - 如何使用 javascript 将过滤器应用于嵌套数组中的所有对象
- ionic4 - 在ionic4中的单个页面中实现选项卡和菜单