Here is another question that's come up a couple of times in various forms:
How does one evaluate a function at all the values in an array? For example, if one defines a function of x, and an array containing certain values of x. Does one define a function f as a variable ($f, say) or as an array (@f, say) that would contain the function evaluated?
To make this more concrete, let's suppose that we have an array of x-values, for example:
@x = (); for ( my $x=0; $x<=10; $x+=0.5 ) { push( @x, $x ); }
(There are a number of subtleties here: (1) note that we use $x
as our increment variable in the for loop, and increment it by 0.5 each time; (2) we use the Perl command push
to push that value on the end of the array @x
; and (3) Perl is quite happy to maintain a scalar variable $x
and an array variable @x
in the same context.)
Now, suppose that we're interested in the function f(x) = sin(x+2). We could define an array of values of this function, and we could define a MathObject for the function and evaluate it at the points in the array. For example, to define the array of function values, we could do the following:
@f = (); foreach my $x ( @x ) { push( @f, sin($x**2) ); }
This uses Perl's sine function to generate the array. Alternately, we could do the same thing with a MathObject function:
$f = Compute( "sin(x^2)" ); @f = (); foreach my $x ( @x ) { push( @f, $f->eval(x=>$x) ); }
Finally, suppose we want to display the values in a table in the text of the problem. The easiest way is probably to use our arrays to do this:
BEGIN_TEXT \{begintable(22)\} \{row( "\(x =\)", @x )\} \{row( "\(f =\)", @f )\} \{endtable()\} END_TEXT
Gavin