I'm working on some pretty intense computation in Mathematica; when my code started running slowly, I tracked the source of the problem to Exp[]
. I need to exponentiate every element of a 50x500x500 array; performing the operation on a 500x500 array takes on the order of 3 seconds (according to AbsoluteTime
), so the entire array should take about 50 times that. Unfortunately, that's calculation needs to happen for every data point.
I've read about lots of ways to speed up Mathematica code, but none of those methods seem to apply here. I'm already working in MachinePrecision
. I have noticed that some of my results are ridiculously small (for example, 4.282835067271648*10^-78127094
), but I'm not sure how to make Mathematica ignore those; they're obviously much smaller than $MachineEpsilon
.
Any advice is greatly appreciated!
Update:
Below is a sample of my code and the generated output. To give it some context, g0
, is a scalar, σg0
is a length 50 array, and g
is a 500x500 array.
(* Added after Oleksandr R.'s comment *)
SetSystemOptions["CatchMachineUnderflow" -> False];
n = Length[σg0];
probgs = ConstantArray[N[0], {50, 500, 500}];
For[i = 1, i <= n, i++,
probgs[[i]] =
N[(1/(Sqrt[2 π] σg0[[i]])) Exp[-0.5 ((g - g0)/σg0[[i]])^2]];
]; // AbsoluteTiming
Precision[probgs]
Output:
{4.816275, Null}
MachinePrecision
Turning off underflow definitely helped; 5 seconds isn't bad at all for what I'm doing.
xxx = RandomReal[{-10, 10}, {50, 500, 500}]; Exp[xxx];
takes about 0.04 seconds for me. $\endgroup$4.282835067271648*10^-78127094
is not aMachinePrecision
number, so actually you are working in arbitrary precision. You have been caught out by automatic underflow handling, whereas clearly you would rather that such numbers go to (machine) zero. EvaluateSetSystemOptions["CatchMachineUnderflow" -> False]
and try again. $\endgroup$Exp[]
at very tiny arguments, you might consider replacingExp[]
with a suitably chosen Padé approximant. $\endgroup$\[Sigma]g0
? Standalone means it should run from a fresh kernel w/o any alterations. The actual arrays matter and you cannot expect other users to bother to generate dummys. $\endgroup$