Reputation: 95
I am a newbie in python sorry for the simple question.
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'.
any help regarding the problem will be appreciated.
Upvotes: 2
Views: 3487
Reputation: 13430
You can use the function np.logaddexp()
to do such operations. It computes logaddexp(x1, x2) == log(exp(x1) + exp(x2))
without explicitly computing the intermediate exp()
values. 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.
Upvotes: 3
Reputation: 140168
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. Both values are strictly equal.
Playing with sys.float_info.epsilon
I tested that:
>>> 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)
...
So you would get exactly 1000.0
as your result even if it worked.
Upvotes: 1
Reputation: 119
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')
Upvotes: 2