## WeBWorK Problems

### passing formulas via Sage

by Joel Trussell -
Number of replies: 3
I want to use Sage to simplify polynomials - I really want to learn to use Sage, so it is not just a problem of simplifying polynomials. Passing formulas is required. I tried a simple example
Context()->variables->are(
s=>"Real"
);

$a1 = random(2,9,1);$a2 = 5;
$a3 = random(1,5,1);$form = Formula("$a1*s +$a2*s + $a3"); Context("Numeric");$SageCode1=<<END;
s = var('s')
print expand($form) END # accepted_tos=>true indicates that you agree to the terms of service: # https://sagecell.sagemath.org/tos.html$result = AskSage($SageCode1,{ accepted_tos=>true, debug=>0}); if (sageReturnedFail($result) ) {
$result = '123456789'; # default value for$answer
}
The printed result looks right, but I can't use it as a formula

$b =$result->eval(s=>2); # this fails - says s not defined in this context
$c =$form->eval(s=>2); # this works

I've tried using Formula($result) with the same error are above. In reply to Joel Trussell ### Re: passing formulas via Sage by Davide Cervone - When you do the Context("Numeric");  just before the sage code, that goes back to a fresh copy of the Numeric context, without the variable s. When the result of the sage computation is turned back into a Formula in WeBWorK, I would guess it uses the current context (I haven't looked at the code for the sage connection to confirm), and so you get the message you are seeing. In reply to Joel Trussell ### Re: passing formulas via Sage by John Travis - Using the sage.pl macro might be a small step in another direction. The code below has what you need backwards but maybe it could be modified to help you out. Here, sageAnswer has the simplified polynomial that you want to check against. The way this is set up gives sageAnswer as the student's response (from inside Sage) rather than what you want to check their response against. It does appear to return from of SageCell though as a formula. DOCUMENT(); loadMacros( "PGstandard.pl", "MathObjects.pl", "contextLimitedPolynomial.pl", "sage.pl" ); TEXT(beginproblem()); Context()->variables->are(s=>"Real");$a1 = random(2,9,1);
$a2 = 5;$a3 = random(1,5,1);
$form = Formula("$a1*s + $a2*s +$a3");

$SageCode = <<SAGE_CODE; s = var('s') ans = expand($form)
SAGE_CODE

Sage(
SageCode=>$SageCode, ); Context()->texStrings; BEGIN_TEXT Expand $$form$$ END_TEXT$ans = $form; # Need this to be the answer student enters above Context()->normalStrings; Context("LimitedPolynomial"); # sageAnswer is the correctly simplified answer generated by the sagecell #$ans needs to be what the student enters
# Perhaps these can be reversed somehow below...?