Eval Versus Substitute

Shows the difference between eval and substitute for MathObject Formulas

Complete Code

Download file: EvalVersusSubstitute.pg

PG problem file

Explanation

DOCUMENT();
loadMacros('PGstandard.pl', 'PGML.pl', 'PGcourse.pl');

Preamble

These standard macros need to be loaded.
$f  = Compute('sqrt(3x + 1)');
$f1 = $f->eval(x => 3);
$f2 = $f->substitute(x => 3);

Context()->variables->add(y => 'Real');
$g = Compute('7xy');
# This next line is an error.
# $g1 = $g->eval(x => 3);
$g2 = $g->substitute(x => 3);
$g3 = $g->eval(x => 3, y => -1);

Context()->flags->set(reduceConstants => 0);
$f3 = $f->eval(x => 3);
$f4 = $f->substitute(x => 3);

Context()->flags->set(reduceConstantFunctions => 0, reduceConstants => 1);
$f5 = $f->substitute(x => 3);

Setup

First, consider $f = Compute('sqrt(3x + 1)') defined in the default context with the default context flags.

  • The eval method returns a number, which is a Value::Real
  • The substitute method returns a Formula which is a Value::Formula

Note that the The Perl command ref used in the problem text returns the type of a blessed object. In this case the objects are MathObjects with type Value::Real or Value::Formula.

Next add the variable y to the context, and consider the function $g = Compute('7xy').

For the function $g, $g->eval(x => 3) throws an error because when the eval method is used a value must be provided for all variables used in the function, and a value for y is not provided.

The next section shows the effect of changing the context flag reduceConstants to 0. Notice that there is no effect on eval, the result is the same number as before, however with substitute the value 3 is substituted for x but left within the formula, which is not reduced.

Lastly, to show the effect of reduceConstantFunctions, if reduceConstants is set to 1 and reduceConstantFunctions to 0, then the inside of the square root is reduced (because it is constant), but the square root remains.

BEGIN_PGML
This shows the difference between [|eval|] and [|substitute|].  Consider the
function [|$f|] [`= [$f]`]. Then

* [|$f->eval(x => 3)|] returns [$f1] and the type is [@ ref $f1 @]
* [|$f->substitute(x => 3)|] returns [$f2] and the type is [@ ref $f2 @]

Next, consider the function [|$g|] [`= [$g]`]. Then

* [|$g->eval(x => 3)|] throws an error.
* [|$g->substitute(x => 3)|] returns [$g2] and the type is [@ ref $g2 @]
* [|$g->eval(x => 3, y => -1)|] returns [$g3] and the type is [@ ref $g3 @]

If [|reduceConstants|] is set to 0 in the flags, then

* [|$f->eval(x => 3)|] returns [$f3]
* [|$f->substitute(x => 3)|] returns [$f4]

If [|reducedConstants|] is set back to 1 and [|reduceConstantFunctions|] is
set to 0, then

* [|$f->substitute(x => 3)|] returns [$f5]
END_PGML

ENDDOCUMENT();

Statement

This is the problem statement in PGML.