0

I will illustrate my problem with this example:

I want to make a function which, given a polynomial, gives me the value of the integral $\int_0^1(ax+bx^2)dx=a/2+b/3$.

Therefore, in this example, I want something like

fun[Poly(x)]:=Coefficient[Poly(x),x,1]/2+Coefficient[Poly(x),x,2]/3;

Do you know how can I define the argument of this function? Because it is a function of $x$ but I want to write the full polynomial of $x$ in the argument.

Thank you for you time!

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
aruera
  • 81
  • 5

2 Answers2

2

One can of course write this in terms of Integrate[], but I had presented an alternative routine, polyInt[], in this previous answer, based on an algorithm due to Kahan. Applied to your example, we have

polyInt[a x + b x^2, {x, 0, 1}]
   a/2 + b/3
J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
1

If x is always the argument:

fun[poly_ /; PolynomialQ[poly, x]] := Expand[poly] /. x^n_. -> 1/(n+1)
fun[a x + b x^2]

a/2 + b/3

If you want to be able to specify the argument:

fun[poly_, arg_] /; PolynomialQ[poly, arg] := Expand[poly] /. arg^n_. -> 1/(n+1)
fun[a x + b x^2, x]

a/2 + b/3

The dot in the pattern x^n_. is a Default pattern that matches both x^n and x (defaulting to n=1 in the latter).

Roman
  • 47,322
  • 2
  • 55
  • 121