Chr*_*kwu -1 python algorithm complexity-theory python-3.x
对于给定的余额和利率,我的计划计算一年内偿还债务的最低月付款.然而,一个平均计算在~0.000150s,另一个计算在~0.000300s.这是否意味着不同程度的渐近复杂性?
这些是代码示例:
较慢的一个:
import time
start_time = time.time()
balance = 999999
annualInterestRate = 0.18
mRate = annualInterestRate/12
high = (((mRate+1)**12)*balance)/12
low = balance/12
guessed = False
def balanceLeft(balance,mRate,minPayment):
monthsLeft = 12
while monthsLeft > 0:
unpaidBalance = balance - minPayment
interest = mRate * unpaidBalance
balance = unpaidBalance
balance += interest
monthsLeft -= 1
return balance
while guessed == False:
minPayment = (high + low) / 2
if round(balanceLeft(balance,mRate,minPayment),2) < 0:
high = minPayment
elif round(balanceLeft(balance,mRate,minPayment),2)> 0:
low = minPayment
else:
if abs(round(balanceLeft(balance,mRate,minPayment),2) - 0) < 0.01:
guessed = True
print('Lowest Payment: ',end='')
print(round(minPayment,2))
print("time elapsed: {:.6f}s".format(time.time() - start_time))
Run Code Online (Sandbox Code Playgroud)
越快越快
import time
start_time = time.time()
annualInterestRate = 0.18
rate = annualInterestRate / 12
monthsLeftr = 12
xCoefficent = 1 + rate
ConstantTerm = 1 + rate
while monthsLeftr > 1:
xCoefficent = (xCoefficent + 1) * ConstantTerm
monthsLeftr -= 1
balance = 999999
monthsLeft = 12
while monthsLeft > 0:
balance = balance * ConstantTerm
monthsLeft -= 1
minPayment = balance / xCoefficent
print('Lowest Payment: ', end="")
print(round(minPayment,2))
print("time elapsed: {:.6f}s".format(time.time() - start_time))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
78 次 |
| 最近记录: |