Why is Python throwing an 'OverFlow' exception on float calculation?
I'm just starting to get into learning Python (Sorry, don't claim homework on this one, because it's not). Just to give myself some meaningful exercises to do to get better with the syntax and features, I've been following this URL: http://www.cs.washington.edu/homes/stepp/bridge/2007/exercises.html
This particular 'Overflow' issue I'm receiving with some floating point calculations is just mystifying me.
This is the error message I get:
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')
Here's my code:
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
I've done everything by trying to typecast input, to use some of the wrapper operations to round or specify decimal point precision. I've even used the Decimal module to try and print out the decimal in string format to see where my logic flaw is.
Any takers on this one to educate me in the realm of floating point calculations in Python?
input()
only gives you a float if it actually sees something that looks like a float; if it looks like an integer then you will get an integer. Use float(raw_input())
instead.
Now, as to the overflow.
Older versions of Python did not promote int
to long
automatically, meaning that the maximum integer you can have is signed 32- or 64-bit; any higher than that results in an overflow. Since you have integers in your expression (see above), you can potentially breach the maximum value for the type, resulting in the exception you're seeing.
精彩评论