I am trying to implement a compiled version for the original algorithm that is supposed to run faster . It works fine for small iteration loop number when max=100. However, when loop number gets greater say max=1000 I get the error. I believe it has something to do with machine precision etc. I do not know how to implement MachineInteger or MachineReal in the code. Suggestions?
{* original algorithm *}
max = 1000;
Clear[a, arg1, fn, cpustart]
cpustart = TimeUsed[];
arg1 = Range[0., max - 1, 1.];
fn = Function[{x}, Block[{a = 7.},
Do[a = 3 a, {i, x}]; a]];
Map[fn, arg1];
(TimeUsed[] - cpustart)
0.643802
{* compiled version algorithm*}
Clear[a, x, arg1, cfn, cpustart]
cpustart = TimeUsed[];
arg1 = Range[0., max - 1, 1.];
cfn = Compile[{x}, Block[{a = 7.}, Do[a = 3*a, {x}]; a]];
Map[cfn, arg1];
(TimeUsed[] - cpustart)
And the output is,
CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation.
CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation.
CompiledFunction::cfne: Numerical error encountered; proceeding with uncompiled evaluation.
General::stop: Further output of CompiledFunction::cfne will be suppressed during this calculation.
1.05929
7.*3^999 // Developer`MachineRealQ
$\endgroup$cfne
errors. $\endgroup$7*3^Range[0, max-1]
is twice as fast as even the compiled code, and does not suffer from machine-precision limits. $\endgroup$