11
$\begingroup$

I have the following code:

Test[a_] := (Print[a]; a*2) Plot[Test[a], {a, 0, 10}, PlotPoints -> 5, MaxRecursion -> 0] 

This should plot a*2 for five points between a = 0 and a = 10, and print whatever a is every time Test[a] is evaluated. Indeed, that's exactly what it does, and this is the output:

0 0.0025025 a 2.5*10^-6 2.40451 5.01127 7.44529 10. 

Most of this is pretty reasonable - I'd expect Plot to try 0, 2.5, 5, 7.5, and 10 - but why is a a value that Plot tries? It's symbolic, so I don't see why it would ever be used in a plot.

Moreover, if I change Test so that it returns Null:

Test[a_] := (Print[a]; a*2;) Plot[Test[a], {a, 0, 10}, PlotPoints -> 5, MaxRecursion -> 0] 

Plot no longer tries any symbolic values at all:

0 0.0025025 2.40451 5.01127 7.44529 10. 

It also no longer tries 2.5*10^-6, though I'm not sure if that's related.

What's going on here? Why is Plot trying symbolic values (and why doesn't it do this when my function returns Null?)

edit: To clarify, this is a minimal working example. I don't actually want to print out the values as a side-effect. I have a compound expression that finds some value I care about and returns that, and when I try and plot the result for different values, it breaks due to having a symbolic variable passed in.

Another trivial example of code that does this, as requested in the answers:

Test[a_] := ( val = Sqrt[a]; Print[a]; solution = val*2; solution) 

The Print[a]; line is only here to show the values of a; this behaviour still occurs when I delete that line.

$\endgroup$
2
  • $\begingroup$Just use '?NumericQ' pattern test on argument(s) to prevent this causing issues w/ your function... I'm sure others will post details (I'm mobile, so terse...)$\endgroup$
    – ciao
    CommentedApr 11, 2015 at 8:58
  • $\begingroup$I did try that, but I still get errors for some reason. It continues to evaluate anyway, and I get errors turning up with NDSolve.$\endgroup$
    – Matthew
    CommentedApr 11, 2015 at 9:04

1 Answer 1

10
$\begingroup$

I believe the symbolic evaluation occurs as part of exclusions detection. If you evaluate the plot with Exclusions -> None the symbolic evaluation doesn't occur.

I suppose when you use a function which returns a non-numeric result such as Null, the system skips the exclusions detection altogether.

$\endgroup$
1
  • $\begingroup$Ah, this solves the immediate problem! Thanks!$\endgroup$
    – Matthew
    CommentedApr 12, 2015 at 12:44

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.