I thought that adding another reduce might do the trick:
$df = $f->D('x')->reduce;
but sadly it did not. Perhaps someone else has a helpful suggestion.
Nota bene: Students do not have to enter the letter "C" as an arbitrary constant. Other letters like "k", "K", or anything that's not "x" will also be accepted by webwork as a constant of integration.
2x^2is that MathObjects is performing the differentiation via the constant multiple rule followed by the power rule, so you get
(2x^2)' = 2(x^2)' = 2*(2x*x') = 2*(2x).
Unfortunately, this is not a form that MathObject knows how to reduce further. If it were
(2*2)x, it would make it
2*(2x) is structurally different, and it doesn't have a reduction rule for that.
MathObjects is not a computer algebra system, and its reduction rules are mostly designed around getting rid of coefficients of 1, or adding 0, or double negatives, or adding a negative, and so on. There are lots of situations that it doesn't know how to handle. It would be possible to extend the reduction rules, but that is the current state of things.
On the other hand, this particular issue can be addressed in a sneaky way. Paul is right that calling
reduce() again won't help (the derivative method already does that). But here's a trick that does help.
Because the two multiplications in
2*(2x) have the same precedence, MathObjects doesn't show the parentheses, and so writes this as
2*2x. If it were to parse that expression, it would do it as
(2*2)x, and so would reduce the constant. So the trick is to ask MathObjects to reparse the resulting expression.
$f = Compute("x^3 + 2x^2+5x")->D; $f = Compute("$f");Here,
"$f"in quotes will force
$fto turn itself into a string, and then that string is passed to
Compute()to be parsed again from scratch. The result should be
3x^2+4x+5, because the original nesting is lost in the conversion to the string.
This doesn't work for all expressions, but for polynomials, it should do what you need.