Argument of a function is another function

6

I would like to know how to put another function as an argument for a function.

For example, let's say that I want to solve an integral by a given numerical integral approximation method. And I want to create a function that does this, in which the arguments of the function are:

Integral = function(a,b, fx)

Where a and b are the integration intervals and fx is the function that I want to integrate.

It's still not working. See:

trapezio.integracao <- function(a, b, fn){ fn(x) }
 {
   x = seq(a, b, by = 0.005)
   n = length(x)

   integral = 0.5*sum((x[2:n] - x[1:(n-1)]) * (f(x[2:n]) + f(x[1:(n-1)]) ) )

   return(integral)
}

fx <- function(x){x^2}

trapezio.integracao(0,1,fx)
    
asked by anonymous 06.12.2016 / 12:22

1 answer

2

Just pass the function as an argument, for example:

funcaoSoma <- function(a,b){a + b}
funcaoAritmetica <- function(a, b, fn){ fn(a,b) }

When you run funcaoAritmetica(2,3,funcaoSoma) , R will execute the function passed by the fn argument and return the value 5.

EDIT:

The function you posted does not work because it does not make the correct use of the function as argument, the correct one would be:

trapezio.integracao <- function(a, b, fn)
 {
   x = seq(a, b, by = 0.005)
   n = length(x)

   //Aqui você irá usar a função passada como argumento,
   // pelo nome de 'fn' (o nome que está indicado na definição da função) e não 'f'

  //No seu exemplo, ficaria assim:
  integral = 0.5*sum((x[2:n] - x[1:(n-1)]) * (fn(x[2:n]) + fn(x[1:(n-1)]) ) )


   return(integral)
}

fx <- function(x){x^2}

In this way, when you run, you will get the following result:

> trapezio.integracao(0,1,fx)
[1] 0.3333375
    
06.12.2016 / 16:29