# Strange integration result

In Mathematica 8, the Integrate command sometimes strangely integrates polynomials yielding unsimplified (and unexpected) fractional results. As an example, the line:

Integrate[((h-x)*(q[1]+q[2])+x*(q[3]+q[4]))^2,{x,0,h}]


The (unsimplified) result is:

h^2/3(-(q[1]+q[2])^3+(q[3]+q[4])^3)/(-q[1]+q[2]+q[3]+q[4])


while the (theoretical) result cannot be a fraction. What are the proper command lines which lead to a polynomial?

-
What's the question? – Rojolalalalalalalalalalalalala Aug 15 '12 at 16:16
The result is not supposed to be a fraction. Is there a command that would help in that direction? – pluton Aug 15 '12 at 16:20
Try Integrate[...] // Expand // Simplify. The reason for this is that the expression with fractions has a smaller LeafCount (39) than your expected result (43). – R. M. Aug 15 '12 at 16:23
Strangely is too subjective for what you described. Maybe it's better to externalize your state. And, as Rojo asked, you didn't make yourself clear what you want. – Silvia Aug 15 '12 at 16:25
Use Together[] on the result. InputForm[Together[Integrate[((h-x)*(q[1]+q[2])+x*(q[3]+q[4]))^2,{x,0,h}]]] Out[5]//InputForm= (h^3*(q[1]^2 + 2*q[1]*q[2] + q[2]^2 + q[1]*q[3] + q[2]*q[3] + q[3]^2 + q[1]*q[4] + q[2]*q[4] + 2*q[3]*q[4] + q[4]^2))/3 – Daniel Lichtblau Aug 15 '12 at 17:27

You need to use Expand and Simplify to get your expected result (without fractions):

Integrate[((h - x)*(q[1] + q[2]) + x*(q[3] + q[4]))^2, {x, 0, h}] // Expand // Simplify
(* 1/3 h^3 (q[1]^2 + q[2]^2 + q[2] (q[3] + q[4]) + (q[3] + q[4])^2 + q[1] (2 q[2] + q[3] + q[4])) *)


The reason Mathematica displayed the form with fractions is because it has a smaller LeafCount than your expected answer:

1/3 h^3 (q[1]^2 + q[2]^2 + q[2] (q[3] + q[4]) + (q[3] + q[4])^2 +
q[1] (2 q[2] + q[3] + q[4])) // LeafCount
(* 43 *)

(h^3 (-(q[1] + q[2])^3 + (q[3] + q[4])^3))/(3 (-q[1] - q[2] + q[3] + q[4])) // LeafCount
(* 39 *)


All the q[i]s introduce additional leaves. If you had done the same integration differently, you'd have gotten the result you were expecting:

Integrate[((h - x)*(p + q) + x*(r + s))^2, {x, 0, h}]
(* 1/3 h^3 (p^2 + q^2 + q (r + s) + (r + s)^2 + p (2 q + r + s)) *)


This has a LeafCount of 32.

-
What about just Cancel? +1 btw – Rojolalalalalalalalalalalalala Aug 15 '12 at 16:38
@Rojo Cancel works too, but has a much higher leaf count – R. M. Aug 15 '12 at 16:39

You can define your own ComplexityFunction to emphasize your avoidance of complex fractions:

compfunc[e_] := Total@Cases[e, Power[expr_, -1] :> LeafCount[expr], {0, Infinity}] +
LeafCount[e]

Integrate[((h - x)*(q[1] + q[2]) + x*(q[3] + q[4]))^2, {x, 0, h}] //
FullSimplify[#, ComplexityFunction -> compfunc] &


1/3 h^3 (q[1]^2 + q[2]^2 + q[2] (q[3] + q[4]) + (q[3] + q[4])^2 + q[1] (2 q[2] + q[3] + q[4]))

-