0
$\begingroup$

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
$\endgroup$
5
  • 1
    $\begingroup$ Does this seem relevant to the problems?: 7.*3^999 // Developer`MachineRealQ $\endgroup$
    – Michael E2
    Jul 23, 2022 at 23:28
  • $\begingroup$ Can you please show how to implement MachineRealQ? Did you mean max=1000//Developer`MachnineRealQ? $\endgroup$
    – Aschoolar
    Aug 23, 2022 at 3:18
  • 2
    $\begingroup$ I think I meant that if you keep multiplying 7 by 3 you’ll eventually get a number greater than can be represented by machine real numbers. At that point you get cfne errors. $\endgroup$
    – Michael E2
    Aug 23, 2022 at 3:40
  • $\begingroup$ As almost always, a better algorithm will be much faster than a compiled bad algorithm. Just calling 7*3^Range[0, max-1] is twice as fast as even the compiled code, and does not suffer from machine-precision limits. $\endgroup$
    – Roman
    Aug 23, 2022 at 5:07
  • $\begingroup$ I see, so it is the end results that gives the error. So I should put some kind of code to handle large value of "a". or " a//Developer`MachineRealQ " $\endgroup$
    – Aschoolar
    Aug 23, 2022 at 9:49

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.