Question

I have some numbers a_i (for i=1 to 10000). I need to compute exp(a_i)/sum(exp(a_j)) using matlab.

Of course, it is impossible to calculate straight away. I found some tricks, the most interesting being:

"Suppose we want to find exp(7.0873e002). This will be a large number indeed but still just barely within matlab's capability of direct calculation. However, we can find the separate exponent and mantissa without calling on 'exp' as follows;

 a = 7.0873e2;
 x = a/log(10);
 D = floor(x); % D will be an integer
 F = 10^(x-D); % F will lie in 1 <= F < 10

Then D will be the power of ten and F the mantissa

 F = 6.27376373225551 % The mantissa
 D = 307 % The exponent (power of ten)

Compare that with the direct answer:

 exp(a) = 6.273763732256170e+307"

I tried something similar, but the result in may case is Inf:

 a = 7.0873e5;
 x = a/log(10);
 D = floor(x);
 F = 10^(x-D);

 exp(a) = Inf

Anyone has an idea?

Was it helpful?

Solution

Your answer is in F and D. Because your a is much larger than the example a (i.e. e5 vs e2) which they state is just barely within Matlab's range, yours must be well out of the range and thus becomes inf. But it doesn't matter because D and F hold your answer, you aren't supposed to be checkin g it against exp(a), the example only calculates exp(a) to demonstrate the proof of concept. But the whole point of this code is to give you a way to find exp of giant numbers.

In your case you get

D =

      307797

and

F =

    3.374110424643062 % Use format long

thus your answer is 3.374110424643062e+307797

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top