Basic programming: Defining functions
The standard form of a function definition
Like any other object, functions must be defined before use. A simple example of this is the definition of the polynomial function \(f(x)=x^3 + x - 1\) .
Sample session in R In the 'console' of R studio you define the function as follows:
> f <- function(x) { x^3 + x - 1 } > f(-2:2) # apply the function f to -2, -1, 0, 1, 2 [1] -11 -3 -1 1 9In a script we usually divide the code over several lines (for readability) and then the definition above looks like as follows:
f <- function(x) {
value <- x^3 + x -1
return(value)
}
But we add one more example: look at the example and then read the explanation.
The function \(e^x\) has the following power series expansion: \[\begin{aligned}e^x &= 1+x+\frac{x^2}{2!}+\frac{x^3}{3!}+\frac{x^4}{4!}+\cdots\\ &= \sum_{k=0}^{\infty}\frac{x^k}{k!}\end{aligned}\] Now suppose that we give polynomial functions \(F_n(x)\) ) as function statement the polynomial that you would get when you cut off the power series after \(n\) terms. So: \[F_n(x)=\sum_{k=0}^{n}\frac{x^k}{k!}\] In this way we get a series of functions \(F_1, F_2, \cdots\) Since we do not want to define each function separately, we construct an R function F
with two arguments, namely \(x\) and \(n\), in the follwing script:
F <- function(x, n) {
sum_of_numbers <- 0
for (k in 0:n) {
sum_of_numbers <- sum_of_numbers + x^k/factorial(k)
}
return(sum_of_numbers)
}
print(F(1, 3)) # rough approximation of the number e
print(F(1, 5)) # good approximation of the number e
print(F(1, 10)) # better approximation of the number e
You get three number of output, viz. 2.66667, 2.716667, and 2.718282, when you run the script. The last instruction shows that the function for \(n=10\) and \(x=1\) returns a numerical result that approximates the exact value of \(e\), the base of the natural logarithm, to an accuracy of 6 decimal places. The deviation of the series approximation from the exact value is called the truncation error of the approximation.