为什么Python在浮点计算时抛出'Overflow'异常?
我刚开始学习Python(抱歉,这不是作业,所以我不求答案)。为了给自己一些有意义的练习,帮助我更好地理解语法和功能,我一直在关注这个网址:http://www.cs.washington.edu/homes/stepp/bridge/2007/exercises.html
我在进行一些浮点数计算时遇到的问题让我感到困惑。
这是我收到的错误信息:
Traceback (most recent call last):
File "./lab0102.py", line 28, in <module>
payment = PMT(r, n, P)
File "./lab0102.py", line 19, in PMT
return round(P * ((r *((1+r)**num_pmts)) / ((1+r)**num_pmts)))
OverflowError: (34, 'Numerical result out of range')
这是我的代码:
import math
#from decimal import Decimal
def PMT(r, n, P):
rate = (r/100)/12
print "rate:", rate
num_pmts = n*12
payment = P * ((r *((1+r)**num_pmts)) / ((1+r)**num_pmts))
return payment
print "This program computes monthly loan payments."
P = input("Loan Amount? ")
n = input("Number of Years? ")
r = input("Interest Rate? ")
payment = PMT(r, n, P)
print "You payment is", payment
我尝试了很多方法,比如转换输入类型,使用一些包装操作来四舍五入或者指定小数点精度。我甚至使用了Decimal模块,试图以字符串格式打印出小数,以找出我的逻辑错误在哪里。
有没有人愿意教我一下Python中浮点数计算的相关知识呢?
1 个回答
2
input()
这个函数只会在输入的内容看起来像浮点数时,才会返回浮点数;如果输入的内容看起来像整数,那它就会返回整数。你可以用 float(raw_input())
来替代。
接下来,关于溢出的问题。
旧版本的Python不会自动把 int
类型提升为 long
类型,这意味着你能表示的最大整数是32位或64位的有符号整数;如果超过这个范围,就会出现溢出。因为你在表达式中使用了整数(见上文),所以有可能会超过这个类型的最大值,从而导致你看到的异常。