对于给定的余额和利率,我的程序计算一年内偿还债务的最低月付款额。 然而,一个在~0.000150秒内平均计算,另一个在~0.000300秒内平均计算,这是否意味着不同程度的渐近复杂性?你知道吗
以下是代码示例:
慢一点的:
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))
快一点的
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))
翻译成一个口头的想法,你试图解决线性方程
a-b*x=0
,在第一个变量通过平分法,在第二个方法通过直接公式x = a/b
。纯粹从描述来看,第二个变量总是更快,因为第一个变量还需要计算a
和b
(resp。b*x
每一步)。你知道吗你经常会发现,对于存在直接解公式的方程,运行这个公式要比任何迭代近似方法快得多。你知道吗
不幸的是,没有那么多的问题类与直接解决方案公式。但在这里,线性问题总是可以直接解决的(对于高维线性系统,效率参数会发生变化)
绝对不是。你知道吗
渐近复杂性从不描述绝对运行时间,而是描述问题规模增大时的趋势。你知道吗
在实践中,对于小问题实例,具有较好渐近复杂度的算法运行速度较慢是非常常见的。你知道吗
不,它们不是同一个程序。第一个有一个while循环,它调用一个有另一个while循环的函数-看起来,这两个循环的复杂性不同。你知道吗
第一个显然是较慢的一个(平方复杂度程序)-第二个没有这样的内部循环,是一个线性复杂度程序。你知道吗
相关问题 更多 >
编程相关推荐