这是一本书中的一个简单练习,要求我们确定在给定利率下,金额翻倍需要多长时间。我的代码是这样的:
def main():
x = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*x:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
它返回的是:
Initial Principal: 1000 Interest rate: 0.5 inf 1734
我的代码有什么问题? 另外我想知道如果我的金额和兴趣很小,上面的代码是否有效,例如amount = 1 和 interest rate = 0.05,因为我猜会包括一些浮点运算。
谢谢!
请您参考如下方法:
罪魁祸首是你写的事实:
while <b>x < 2*x</b>:
由于 x > 0,该关系将始终为 False,您不比较新的 x使用旧的 x,将新的 x 与两倍的新 x 进行比较。
我们可以使用存储初始金额的变量 x0 有效地解决这个问题:
def main():
x = <b>x0</b> = eval(raw_input("Initial Principal: "))
y = eval(raw_input("Interest rate: "))
count = 0
while x < 2*<b>x0</b>:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
但是代码还是有些问题。例如,您使用 eval。不要使用 eval 除非绝对必要:现在一个人可以输入任何类型的 Python 代码,也可以输入会破坏系统的代码。使用 float(..) 将 str 转换为 int:
def main():
x = x0 = <b>float</b>(raw_input("Initial Principal: "))
y = <b>float</b>(raw_input("Interest rate: "))
count = 0
while x < 2*x0:
x = x * (1 + y)
count = count + 1
print (x)
print (count)
main()
但现在的代码仍然效率低下。有一种使用对数快速计算年数的方法:
<b>from math import log, ceil, pow</b>
def main():
x = x0 = float(raw_input("Initial Principal: "))
y = float(raw_input("Interest rate: "))
count = <b>ceil(log(2.0, y+1.0))</b>
<b>newx = x * pow(1.0+y, count)</b>
print (newx)
print (count)
