9.50 MakeFunctionΒΆ

It is sometimes useful to be able to define a function given by the result of a calculation.

Suppose that you have obtained the following expression after several computations and that you now want to tabulate the numerical values of f for x between -1 and +1 with increment 0.1.

expr := (x - exp x + 1)^2 * (sin(x^2) * x + 1)^3
\[\]
(x3ex2+(-2x4-2x3)ex+x5+2x4+x3)sin(x2)3+(3x2ex2+(-6x3-6x2)ex+3x4+6x3+3x2)sin(x2)2+(3xex2+(-6x2-6x)ex+3x3+6x2+3x)sin(x2)+ex2+(-2x-2)ex+x2+2x+1

Type: Expression Integer

You could, of course, use the function evalevalExpression within a loop and evaluate expr twenty-one times, but this would be quite slow. A better way is to create a numerical function f such that f(x) is defined by the expression expr above, but without retyping expr! The package MakeFunction provides the operation functionfunctionMakeFunction which does exactly this.

Issue this to create the function f(x) given by expr.

function(expr, f, x)
\[\]
f

Type: Symbol

To tabulate expr, we can now quickly evaluate f 21 times.

tbl := [f(0.1 * i - 1) for i in 0..20];
\[\]
[0.00053918440362701574,0.00396575511844206653,0.008854518748339836892,0.01165248830907069695,0.010861822092457513645,0.0076366823212086996506,0.0040584985759782206255,0.0015349542891050083648,0.00034249031549879905716,0.000023330482760988196001,0.0,0.000026818687828625994229,0.00046915713720051642621,0.0026924576596851958608,0.010148688173691351488,0.031383372585438105643,0.087699114451546152979,0.23130197893439968362,0.5843743955958098772,1.4114930171992819197,3.221694827675164252]

Type: List Float

Use the list [x1,...,xn] as the third argument to functionfunctionMakeFunction to create a multivariate function f(x1,...,xn).

e := (x - y + 1)^2 * (x^2 * y + 1)^2
\[\]
x4y4+(-2x5-2x4+2x2)y3+(x6+2x5+x4-4x3-4x2+1)y2+(2x4+4x3+2x2-2x-2)y+x2+2x+1

Type: Polynomial Integer

function(e, g, [x, y])
\[\]
g

Type: Symbol

In the case of just two variables, they can be given as arguments without making them into a list.

function(e, h, x, y)
\[\]
h

Type: Symbol

Note that the functions created by functionfunctionMakeFunction are not limited to floating point numbers, but can be applied to any type for which they are defined.

m1 := squareMatrix [ [1, 2], [3, 4] ]
\[\]
[1234]

Type: SquareMatrix(2,Integer)

m2 := squareMatrix [ [1, 0], [-1, 1] ]
\[\]
[10-11]

Type: SquareMatrix(2,Integer)

h(m1, m2)
\[\]
[-78368960-1713219588]

Type: SquareMatrix(2,Integer)

For more information, see ugUserMakePage in Section ugUserMakeNumber .