简体   繁体   English

如何在python中处理64float精度的指数溢出?

[英]How to deal with exponent overflow of 64float precision in python?

I am a newbie in python sorry for the simple question. 我是python的新手,抱歉这个简单的问题。

In the following code, I want to calculate the exponent and then take the log. 在下面的代码中,我想计算指数然后获取日志。

Y=numpy.log(1+numpy.exp(1000))

The problem is that when I take the exponent of 710 or larger numbers the numpy.exp() function returns 'inf' even if I print it with 64float it prints 'inf'. 问题是,当我使用710或更大数字的指数时,numpy.exp()函数返回'inf',即使我用64float打印它也会输出'inf'。

any help regarding the problem will be appreciated. 任何有关该问题的帮助将不胜感激。

You can use the function np.logaddexp() to do such operations. 您可以使用函数np.logaddexp()来执行此类操作。 It computes logaddexp(x1, x2) == log(exp(x1) + exp(x2)) without explicitly computing the intermediate exp() values. 它计算logaddexp(x1, x2) == log(exp(x1) + exp(x2))而不显式计算中间exp()值。 This avoids the overflow. 这可以避免溢出。 Since exp(0.0) == 1 , you would compute np.logaddexp(0.0, 1000.0) and get the result of 1000.0 , as expected. 由于exp(0.0) == 1 ,您将计算np.logaddexp(0.0, 1000.0)并获得1000.0的结果,如预期的那样。

Use the decimal library: 使用十进制库:

>>> import numpy as np
>>> np.exp(1000)
inf
>>> from decimal import Decimal
>>> x = Decimal(1000)
>>> np.exp(x)
Decimal('1.970071114017046993888879352E+434')

Check this out: 看一下这个:

>>> x = numpy.exp(100)
>>> y = x+1
>>> y==x
True

so even with 100 (which computes all right), adding 1 (or even a very big number), the lowest value is absorbed and has absolutely no effect in the addition. 因此,即使100 (计算得很好),加1(或甚至非常大的数字),最低值被吸收,并且在添加中绝对没有效果。 Both values are strictly equal. 两个值都严格相等。

Playing with sys.float_info.epsilon I tested that: 使用sys.float_info.epsilon我测试了:

>>> numpy.log(1e20+numpy.exp(100))==numpy.log(numpy.exp(100))
True
>>> numpy.log(1e30+numpy.exp(100))==numpy.log(numpy.exp(100))
False

so even a value like 1e20 is absorbed by exp(100) ... 因此即使像1e20这样的值被exp(100)吸收......

So you would get exactly 1000.0 as your result even if it worked. 所以即使它有效,你的结果也会得到1000.0

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

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