User-defined functions

  1. Overview
  2. Variable scope
  3. Differentiable functions

Overview

Define new functions the same way you would using pen and paper.

Example:


f(x) = x*x + 3*x -5
f(x) = x*x + 3*x -5
3*f(5)
105

Functions can be defined in terms of library functions:

Example:


g(x,y) = x*y - atan(y/x)
g(x,y) = x*y - atan(y/x)

You may define functions of several variables. The arguments can be scalars, boolean, arrays, matrices or other functions. The type used by the function is resolved at run time.

For example, function h(p) below finds the maximum entry and returns it squared:


h(p) = ( v=max(p) ) * v
h(p) = ( v=max(p) ) * v

Function h(p) above can be used with arrays or matrices:


h( (4, 3, 6, 2) )
36
B = (3, 5 ; 7, 2 ; 3 5 )
3  5
7  2
3  5
h(B)
49

Function h(p) still works if the argument is a scalar:


h(9)
81

Once a user function has been created, you may use it in the definition of another function:

Example:


log2(x) = log(x)/log(2.)
log2(x) = log(x)/log(2.)
f(x) = x*log2( x+2 )
f(x) = x*log2( x+2 )

User functions may return any type of value (boolean, array, matrix, etc.)

Example of a boolean being returned:


// Function returns a boolean
f(x,y) = x>0 && x < y
f(x,y) = x>0 && x < y
f(-1,4)
false

In this example, a unit vector is returned:


f(x) = if( x==1 ) return (1,0,0); else if( x==2 ) return (0,1,0); else return (0,0,1)
f(x) = if( x==1 ) return (1,0,0); else if( x==2 ) return (0,1,0); else return (0,0,1)
f(2) dot (4,-5, 2)
-5

Variable scope

User-defined functions are of two types. If the function you create uses curly brackets it is considered a program. Programs have different rules; for more information on user-defined programs see section Programming.

Simple user-defined functions are usually created in one line. The next example shows a fundamental property of variable scope:


m=3
3
f(x) = x*m/2
f(x) = x*m/2
f(5)
15/2

The example above shows that simple functions look for variables in the global scope. Notice that variable m is searched in the global scope at runtime. If the value of m changes, function f changes automatically as shown below:


m=7
7
f(5)
35/2

Differentiable functions

User-defined functions are differentiable if the function definition does not make use of curly brackets and it is differentiable in the sense of standard Calculus. To test whether a function is differentiable (in the Calcugator sense) use function isDifferentiable.

Example:


f(x)=x*sin(x)-e^x
f(x)=x*sin(x)-e^x
isDifferentiable(f)
true

Example:


g(x)={y=x*x; return y;}
g(x)={y=x*x; return y;}
isDifferentiable(g)
false

Differentiable functions can be processed using the symbolic toolkit. See the Symbolic Toolkit for more information.