Some Common Issues with Functions
Some aspects of defining functions (e.g., for differentiation or plotting) can be confusing. In this section we try to address some of the relevant issues.
Here are several ways to define things which might deserve to be called “functions”:
Define a Python function, as described in Functions, Indentation, and Counting. These functions can be plotted, but not differentiated or integrated.
In the last line, note the syntax. Using "plot(f(z), 0, 2)" instead will give a "NameError", because "z" is a dummy variable in the definition of "f" and is not defined outside of that definition. In order to be able to use "f(z)" in the plot command, "z" (or whatever is desired) needs to be defined as a variable. We can use the syntax below, or in the next item in our list.
At this point, "f(z)" is a symbolic expression, the next item in our list.
Define a “callable symbolic expression”. These can be plotted, differentiated, and integrated.
Note that while "g" is a callable symbolic expression, "g(x)" is a related, but different sort of object, which can also be plotted, differentated, etc., albeit with some issues: see item 5 below for an illustration.
Use a pre-defined Sage ‘calculus function’. These can be plotted, and with a little help, differentiated, and integrated.
By itself, "sin" cannot be differentiated, at least not to produce "cos".
Using "f = sin(x)" instead of "sin" works, but it is probably even better to use "f(x) = sin(x)" to define a callable symbolic expression.
Here are some common problems, with explanations:
Accidental evaluation.
The issue: "plot(h(x), 0, 4)" plots the line y=x-2, not the multi-line function defined by "h". The reason? In the command "plot(h(x), 0, 4)", first "h(x)" is evaluated: this means plugging the symbolic variable "x" into the function "h". So, the inequality "x < 2" evaluates to "False" first, and hence "h(x)" evaluates to "x - 2". This can be seen with
Note that here there are two different "x": the Python variable used to define the function "h" (which is local to its definition) and the symbolic variable "x" which is available on startup in Sage.
The solution: don’t use "plot(h(x), 0, 4)"; instead, use
Accidentally producing a constant instead of a function.
The problem: "g(3)", for example, returns an error, saying “ValueError: the number of arguments must be less than or equal to 0.”
"g" is not a function, it’s a constant, so it has no variables associated to it, and you can’t plug anything into it.
The solution: there are several options.
Define "f" initially to be a symbolic expression.
Or with "f" as defined originally, define "g" to be a symbolic expression.
Or with "f" and "g" as defined originally, specify the variable for which you are substituting.
Finally, here’s one more way to tell the difference between the derivatives of "f = x" and "f(x) = x"
As this example has been trying to illustrate, "h" accepts no arguments, and this is why "h(3)" returns an error.