More Complicated Functions

If a function definition has more than one line of statements, the keyword function should be used. The syntax is
function_name = function (input_arguments) -> (output arguments)
                    ... // a bunch of statements
                end
Note that in the body of the function, the input arguments can be used as if they are variables (but they are not visible outside the function), and the output arguments should be given values before the end of the function. The following function evaluates the Taylor expansion of $ \cos(x)$ function for a small $ x$ value

$\displaystyle \cos x \approx \sum_{n=0}^{N} (-1)^n\frac{x^{2n}} {(2n)!}
$

cos_taylor = function (x, N) -> v
       v = 1;
       vk = 1;
       xsq = x * x;
       for k = 1 : N
           vk = - vk * xsq / (2 * k) / (2 * k - 1);
           v += vk;
       end
end



oz 2009-12-22