eval()
, the answer will be numeric, and the structure of the formula from which it came will be lost. There is, however, a way to keep a formula that has the original structure. It requires that you turn off automatic reduction of constants, and use substitute()
rather than eval()
, at least for the first step. Here,
Context()->flags->set( reduceConstants => 0, reduceConstantFunctions => 0, ); $m = $g->substitute(x=>$a);would cause $m to be a formula that would display as
2 cos(2 a) where "a" is replaced by the value of $a
.
But you don't want
$m
to be a formula, you want it to be a number, but still display as 2cos(2a)
. The correct answer string is actually a property of the MathObject itself, so you could evaluate it and set that correct answer string to
$m->string
, but that is painful.
Fortunately, Compute()
has a side-effect of note only evaluating the expression, but also setting the correct answer to be exactly the string that was passed to it. So Compute("2cos(2*$a)")
would use the numeric value as the correct answer (not a formula) while still displaying 2cos(2*a)
as the correct answer. So one approach here would be to do
Context()->flags->set( reduceConstants => 0, reduceConstantFunctions => 0, ); $m = Compute($g->substitute(x=>$a)->string);This will substitute $a into the original formula, turn the result back into a string, and the reparse that string as a MathObject, setting the correct answer to be the string with the substituted value.
Finally, note that you don't want to put quotes around $m
in your PGML answer (as that would force the expression to be turned into a string again and re-parsed, which would lose the correct answer that you carefully set with Compute()
above. So the crucial part of your problem would be
Context("Numeric"); Context()->flags->set( reduceConstants => 0, reduceConstantFunctions => 0, ); $a = random(2,9,1); $f = Formula("sin(2x)"); $g = $f->D; $m = Compute($g->substitute(x=>$a)->string); ####################################################### # # Find the derivative of f(x) = sin(2x) at a random point. # BEGIN_PGML The derivative of [` f(x) = [$f] `] at [` x = [$a] `] is [_______]{$m}. END_PGML