2
$\begingroup$

I want to define a function called int that takes another function as an argument and yields an integral of that function from 0 to 1 (just for example).

So I tried:

int[f_]:= NIntegrate[f[x],{x,0,1}]

This now works like this:

int[Cos]
0.841471

or

int[Sin]
0.459698

However, if I want a specific function, like x Sin[E^x], I need to write this:

int[# Sin[Exp[#]]&]
0.411229

How do I define the function int so that it will work like

int[x Sin[Exp[x]]

or

int[t Sin[Exp[t]]

with any letter as an argument and yield the result?

I tried also this:

int[f_[x_]] := NIntegrate[f[x], {x, 0, 1}]

While int[Sin[t]] yields the correct result, int[t Sin[t]] just returns int[t Sin[t]].

$\endgroup$
  • $\begingroup$ If you consider the syntax of Plot, Table, Integrate, etc., the variable is specified when the argument is an algebraic expression and not literally a function. E.g. a syntax of the form int[t Sin[t], t] identifies the variable (in the 2nd argument). $\endgroup$ – Michael E2 Jun 13 '18 at 22:05
4
$\begingroup$

With an automatic extraction of the independent variable:

int[f_] := With[{var = Reduce`FreeVariables[f][[1]]}, 
  NIntegrate[f, {var, 0, 1}]]

so that

int[x Sin[Exp[x]]]

0.411229

but also

int[t Sin[Exp[t]]]

0.411229

And for example:

int[Cos@Cos@Cos@zzz]

0.786287

$\endgroup$
  • 1
    $\begingroup$ Both of your answers are very nice, but I like this one more (I've never heard of FreeVariables)... $\endgroup$ – user16320 Jun 13 '18 at 22:46
  • $\begingroup$ This is pretty cool; can you talk a little about what Reduce`FreeVariables[f]does? I'm having trouble finding a description of `FreeVariables in the help files. $\endgroup$ – Rudy Potter Jun 14 '18 at 0:05
  • 1
    $\begingroup$ If you went to the linked answer, you'd see it's an undocumented function. Btw, for a bunch of undocumented functions see What are some useful, undocumented Mathematica functions? $\endgroup$ – corey979 Jun 14 '18 at 7:19
2
$\begingroup$

Try leaving the "[x]" out of the definition.

int[f_] := NIntegrate[f, {x, 0, 1}];
int[x Sin[Exp[x]]]
0.411229

If you need to be able to change the variable, you could do:

int2[fun_, var_] := NIntegrate[fun, {var, 0, 1}]
int2[x Sin[Exp[x]], x]
0.411229
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.