## WeBWorK Main Forum

### Fractional Powers

by Andrew Dabrowski -
Number of replies: 2
I'm running into a problem when I combine the Fraction-NoDecimals context with a fractional power in a formula.  I've attached a mwe pg file:

DOCUMENT();

"PGstandard.pl",
"MathObjects.pl",
"PGML.pl",
"contextFraction.pl"
);

SRAND(1355);

TEXT(beginproblem());

Context()->variables->set(x=>{limits=>[1,4]});

$n3 = random(2,9,1); do {$n4 = random(2,9,1); } until ( gcd($n3,$n4) == 1 );

$F = Compute("x^($n3/$n4)");$ans = Compute("$F+C"); BEGIN_PGML [ F(x) = [$F] ]

[F(x)  = ]
[___________________________________]{$F->cmp()} [F(x)+C = ] [___________________________________]{$ans->cmp()}
END_PGML

ENDDOCUMENT();

Here's the result:

Somehow x^(2/7) became x^2/7 when adding C.

Am I doing something wrong?  Or is this a bug?

### Re: Fractional Powers

by Davide Cervone -

It turns out that this is due to an error in the Fraction context that doesn't properly insert parenthesis in some circumstances when the fraction is turned into a string. Since you use

$ans = Compute("$F+C");


The value of $F is first turned into a string, inserted into the larger string, and then re-parsed to form the new MathObject. Because the parentheses are missing, it is equivalent to $ans = Compute("(x^2/7)+C");


which is ((x^2)/7)+C, not (x^(2/7))+C, leading to your issue.

One solution would be to use

$ans =$F + "C";


instead. Since \$F is already a Formula object, it will handle the + by doing addition of Formulas, first converting the string "C" into a Formula, and returning the new Formula that is their sum. This avoids the stringification and re-parsing that your original method uses (so is also more efficient).

See if that does the trick for you.

I've made a pull request to fix the problem. So a second solution would be to download the updated contextFractions.pl file from that PR and save it to your course's templates/macros directory (or to the main pg/macros directory if you have access to that).