简体   繁体   English

检索引起运行时警告的数组元素

[英]Retrieve array element that caused a runtime warning

When I apply numpy.exp to an array of numbers I get the following runtime warning: 当我将numpy.exp应用于数字数组时,会收到以下运行时警告:

RuntimeWarning: overflow encountered in exp

Now I know that some value in this array caused the result of exp to overflow but I don't know which one (and this array has millions of entries). 现在,我知道该数组中的某些值导致exp的结果溢出,但是我不知道哪个(该数组有数百万个条目)。

Is there a way to make this runtime warning more verbose in a sense that it also displays the specific argument that caused the overflow (and more importantly its position in the input array)? 从某种意义上说,它还可以显示导致溢出的特定参数(更重要的是其在输入数组中的位置),是否有办法使运行时警告更详细? I discovered seterr and seterrcall however they don't seem to incorporate what caused the error (only what the error is about). 我发现了seterrseterrcall,但是它们似乎并没有合并导致错误的原因(仅是有关错误的原因)。


I know that - after encountering this warning - I could pass each value in the array separately to exp and watch out for the warning or that I could use isfinite to test the elements of exp(array) . 我知道-遇到此警告后-我可以分别将数组中的每个值传递给exp并注意警告,或者可以使用isfinite来测试exp(array)的元素。 However this implies messing with the actual code while I would prefer that numpy does this kind of things behind the scenes (being configured appropriately). 但是,这意味着弄乱了实际的代码,而我希望numpy在幕后进行此类操作(配置适当)。


Edit: I was asked to post some code that reproduces the error. 编辑:我被要求张贴一些代码,重现该错误。 Here it is: 这里是:

>>> import numpy
>>> array = numpy.zeros((10,), dtype=float)
>>> array[0] = 1.0e308
>>> numpy.exp(array)
__main__:1: RuntimeWarning: overflow encountered in exp
array([ inf,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.,   1.])

I would like to know that it was the element with index 0 that caused to overflow (not just that an overflow happened somewhere). 我想知道导致索引溢出的是索引为0的元素(而不仅仅是某处发生了溢出)。

The problem is just that exp(1e308) is too big for float ! 问题是exp(1e308)对于float来说太大了!

If you consider the exp function, knowing that 1.7976931348623157e+308 is the maximum value for a float, remove from your array all the value below log(1.7976931348623157e+308) = 709 如果考虑使用exp函数,并且知道1.7976931348623157e+308是浮点型的最大值,请从数组中删除log(1.7976931348623157e+308) = 709以下的所有值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM