Different output from same code with exponents in python

隐身守侯 提交于 2019-12-14 02:53:22

问题


I'm running some code in a loop, which runs for many thousands of data points, where at one point I have this line of code:

z[i, j] = -math.exp(oneminusbeta[j, i])

I put comments before each line of code, and the last line comment outputted before the code crashed was this:

z[30416,20] = -math.exp(oneminusbeta (which is 8.04812689598e-13))

The error was:

OverflowError: math range error

Which means that the above line caused the crash. However, when I open a separate console and type this

a = -math.exp(8.04812689598e-13)
print str(a)

My code doesn't crash. It just outputs:

-1.0

What's going on? Why is it that in the middle of a bunch of code, raising an exponent to this power makes the program crash, but it doesn't crash otherwise? What can I do to prevent this? Or how do I know when python will decide some exponent is too much to deal with and suddenly crash?

Edit

Similar to the way I initialized z, I just tried this:

a = np.empty([1,1]) 
a[0,0] = -math.exp(8.04812689598e-13) 
print str(a)

But this doesn't crash either.

Edit 2

Someone suggested that the error might be caused by the line after the comment output. The line after the one I mentioned looks like this:

weights[i,j] = math.exp(beta[j,i] + oneminusbeta[j,i])

Edit 3

I ran the code again and whilst in the above example, the code crashed on weights[30816, 42], this time it crashed on weights[55399, 43]. Which means that this time it didn't overflow on the same spot it overflowed above, but in another spot. Which means that it isn't really an issue of python not being able to do the calculation.

But I'm using exactly the same dataset as before. What's going on and is there any solution to this arbitrary issue? I'm using Anaconda Spyder on a 64-bit machine.

来源:https://stackoverflow.com/questions/25802670/different-output-from-same-code-with-exponents-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!