| |||||||||||
|
How about a serious 'variables' function?
Map ListThe Derive in-built function MAP_LIST( ) is very useful. As a simple example, suppose we want to create, say, a vector of twenty variables for use within a function: vars(z, n) := MAP_LIST(APPEND(STRING(z), r), r, 1, n) So vars(q, 20) simplifies to [q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13, q14, q15, q16, q17, q18, q19, q20] Or to achieve a similar effect, how about: vars(z, n) := VECTOR(APPEND(STRING(z), r), r, 1, n) As a simpler example of map_list, and to avoid the function nesting above, here is another one. Take a list (vector): [3, 4, 5], and square all the elements: MAP_LIST(x2 , x, [3, 4, 5]) [9, 16, 25] In this example, we are mapping the function x2, for variable x, to the vector [3, 4, 5]. Similarly, MAP_LIST(x2y,
x, [3, 4, 5]) MAP_LIST(xy, y, [3, 4, 5]) [ 3·x , 4·x , 5·x ] If we now consider the Fibonacci sequence, as described in the append section. The solution vector is given by [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144]. So, we now need to take natural logs of each element: MAP_LIST(LN(x), x, [1, 1, 2, 3, 5, 8, 13,
21, 34, 55, 89, 144]) At this point, we can introduce Derive's very useful FIT() function. Taking logs of the Fibonacci sequence may look linear, but is it? A least-squares fit of the data points should help. To allow plotting of these points (y co-ordinates), we need to create a matrix containing corresponding x co-ordinates. The function to create a Fibonacci sequence referred to here is:
or in 1-D fib(z, x := [1], n := 1) := LOOP(IF(n > z, RETURN REVERSE(x)), x := ADJOIN(n, x), n :+ FIRST(REST(x))) And the function which takes the necessary natural logs is:
Again, in the Entry bar in 1-D this would be: fibona(q, a) := PROG(a := fib(q), [[0, ..., DIM(a) - 1], MAP_LIST(LN(x), x, a)]`) So, fibona(200) This returns the following pairs of data points, which can be plotted, as well as tested for a linear fit:
As an example of using Derives' FIT() command, the above pairs of data points can be used to find a least squares fit. For a linear fit (that is, a constant plus some co-efficient of x-only): the general form is FIT([h,a+bh], [x,y]) where [x,y] is the above 12 x 2 matrix of co-ordinates. Explicitly,
and the solution on approximating this is 0.4727h-0.2597 which, when plotted, is a straight line very close to the above data points. To extend the fit() function to non-linear a fit, the format is
and again approximating to give 0.00049h4-0.0121h3+0.1009h2+0.175h-0.0728
| ||||||||||||||||