]>
Book Contents Previous Section 9.49 Magma Next Section 9.51 MappingPackage1 Book Index

## 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

(x 3 e x 2+(-2 x 4-2 x 3)e x+x 5+2 x 4+x 3)sin(x 2)3+(3 x 2 e x 2+(-6 x 3-6 x 2)e x+3 x 4+6 x 3+3 x 2)sin(x 2)2+(3 x e x 2+(-6 x 2-6 x)e x+3 x 3+6 x 2+3 x)sin(x 2)+e x 2+(-2 x-2)e x+x 2+2 x+1

Type: Expression Integer

You could, of course, use the function eval eval Expression 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 function function MakeFunction 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.0005391844 0362701574,0.0039657551 1844206653,0.0088545187 4833983689 2,0.0116524883 0907069695,0.0108618220 9245751364 5,0.0076366823 2120869965 06,0.0040584985 7597822062 55,0.0015349542 8910500836 48,0.0003424903 1549879905 716,0.0000233304 8276098819 6001,0.0,0.0000268186 8782862599 4229,0.0004691571 3720051642 621,0.0026924576 5968519586 08,0.0101486881 7369135148 8,0.0313833725 8543810564 3,0.0876991144 5154615297 9,0.2313019789 3439968362,0.5843743955 958098772,1.4114930171 992819197,3.2216948276 75164252]

Type: List Float

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

e := (x - y + 1)**2 * (x**2 * y + 1)**2

x 4 y 4+(-2 x 5-2 x 4+2 x 2)y 3+(x 6+2 x 5+x 4-4 x 3-4 x 2+1)y 2+(2 x 4+4 x 3+2 x 2-2 x-2)y+x 2+2 x+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 function function MakeFunction 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] ]

[1 2 3 4]

Type: SquareMatrix(2,Integer)
m2 := squareMatrix [ [1, 0], [-1, 1] ]

[1 0-1 1]

Type: SquareMatrix(2,Integer)
h(m1, m2)

[-7836 8960-17132 19588]

Type: SquareMatrix(2,Integer)

For more information, see ugUserMakePage in Section ugUserMakeNumber .

Book Contents Previous Section 9.49 Magma Next Section 9.51 MappingPackage1 Book Index