PREP 2014 Question Authoring - Archived

How does one suppress terms with coefficient 0 in text display?

Re: How does one suppress terms with coefficient 0 in text display?

by Davide Cervone -
Number of replies: 0
There are two things at play, here. The first is that Compute() does just what it says, it computes the value of the equation and returns that. The result is a real number, not a formula, and real numbers don't have a tree structure like a formula does.

On the other hand, Compute() does first parse the string as a formula, and then if it is constant it returns that constant value rather than the formula itself. But Compute() does retain the original formula and makes it available via the original_formula property of the returned MathObject. So the original formula could be obtained from

    $ans->{original_formula}
in your case.

The problem, however, is that, by default, constant values within a formula are reduced automatically, so the results of 1/$b and the addition of $a will be performed during the parsing of the formula, so the original formula will also just be the final number.

You can control that automatic evaluation using some flags set in the Context. So

    Context()->flags->set(
      reduceConstants => 0,
      reduceConstantFunctions => 0,
    );
will prevent reducing of constant operations and constant function calls, leaving the original formula as the numeric expression you have in mind. That means
    Context()->flags->set(
      reduceConstants => 0,
      reduceConstantFunctions => 0,
    );
    
    $a = non_zero_random(-5,5,1);
    $b = random(2,10,1);
    
    $ans = Compute("$a+1/$b"); 
    
    Context()->texStrings;
    BEGIN_TEXT
    The answer is \($ans->{original_formula}\).
    END_TEXT
    Context()->normalStrings;
should do what you ask.