5
$\begingroup$

e.g. when Mathematica Calculating f[x0]=A[x0] B[x0], where A[x] & B[x] could be some complicated high dimensional function.

Will Mathematica outcome 0 directly when A[x0]=0, instead of still calculating B[x0]?

$\endgroup$
6
  • $\begingroup$ As far as i understand mma in its processes of internal calculations, will generally follow the typical (), / z, +- rules and then see if 0 or a 1/0 is somewhere in the calculation as it goes through it process, should A[x] === 0 and that’s immediately given, and depending on the internal function rules, it will likely report 0 $\endgroup$ Commented Dec 20, 2021 at 8:40
  • $\begingroup$ Correction: f[x0_?NumericQ] := Module[{Ax0 = A[x0]}, If[Ax0 == 0, 0, Ax0*B[x0]]]; $\endgroup$
    – Bob Hanlon
    Commented Dec 20, 2021 at 17:03
  • 2
    $\begingroup$ A few reasons why 0 does not shortcut evaluations are: 0 × Infinity evaluates to Indeterminate, 0 × Undefined evaluates to Undefined, 0 × 1.0 evaluates to 0. (Real rather than Integer), 0 × IdentityMatrix[2] evaluates to {{0, 0}, {0, 0}} (matrix rather than Integer), etc. $\endgroup$ Commented Dec 20, 2021 at 18:05
  • $\begingroup$ @Bob Hanlon Thanks for your solution! $\endgroup$ Commented Dec 21, 2021 at 1:24
  • $\begingroup$ @Vladimir Reshetnikov Thanks! Now I understand it in detail. $\endgroup$ Commented Dec 21, 2021 at 1:24

1 Answer 1

7
$\begingroup$

A quick experiment shows it does not stop, but it will evaluates all expressions on RHS, even if one is zero.

f1[x_] := 0
f2[x_] := (Do[PrimeQ[n], {n, 1, 10000000}]; 1)
f1[x]*f2[x]

It still called f2[x]

Even doing this

f1[x_] := 0
f2[x_] := (Do[PrimeQ[n], {n, 1, 10000000}]; 1)
Evaluate[f1[x]]*f2[x]

had no effect. It is still slow, because it evaluated f2[x]

Even this

f2[x_] := (Do[PrimeQ[n], {n, 1, 10000000}]; 1)
0*f2[x]

had no effect. It is still slow, because it evaluated f2[x]

$\endgroup$
3
  • 5
    $\begingroup$ Times does not have a HoldAll attribute, so it HAS to evaluate everything. Functions that are capable of short-circuit evaluation such as Or and And have hold attributes for this reason. $\endgroup$ Commented Dec 20, 2021 at 8:47
  • $\begingroup$ @SjoerdSmit Sure. I understand. The OP is using Times as the example they give. $\endgroup$
    – Nasser
    Commented Dec 20, 2021 at 8:48
  • $\begingroup$ succinct and clear! $\endgroup$ Commented Dec 20, 2021 at 8:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.