Doing mathematics with R: Functions
Multiple returns and returned values
Sample session in R with multiple return statements
> sign_function <- function(x) { + if (x<0) { + return(-1) + } else if (x>0) { + return(1) + } else { + return(0) + } + } > sign_function(-3) [1] -1 > sign_function(3) [1] 1 > sapply(-2:2, sign_function) # apply the function to each of the vector components
[1] -1 -1 0 1 1
We modify the earlier example of approximating \(e^x\) with polynomial functions to return both the function values and the truncation error. We also use function F
within a second function called tabulate
, which prints a table of the results of a systematic inspection of the truncation errors for a given \(x\)
Delivery of multiple values
The R script below
F <- function(n, x) { sum_of_numbers <- 0 for (k in 0:n) { sum_of_numbers <- sum_of_numbers + x^k/factorial(k) } trunctation_error <- abs(sum_of_numbers - exp(x)) return(list(value=sum_of_numbers, error=truncation_error)) } result <- F(10,1) cat("returned value =", result$value, "\n") cat("trunction arror =", result$error, "\n") tabulate <- function(x) { table_of_results <- "" table_of_results <- cat(table_of_results,
sprintf("\nx = %g, exp(x) = %g\n", x, exp(x))) table_of_results <- cat(table_of_results, sprintf("n F(x) truncation error\n")) for (n in c(2, 4, 6, 8, 10)) { result <- F(n,x) table_of_results <- cat(table_of_results, sprintf("%-7g %-7f %.8f",
n, result$value, result$error), "\n") } cat(table_of_results) } tabulate(1)
returns the following output:
returned value = 2.718282
truncation error = 2.731266e-08
x = 1, exp(x) = 2.71828
n F(x) truncation error
2 2.500000 0.21828183
4 2.708333 0.00994850
6 2.718056 0.00022627
8 2.718279 0.00000306
10 2.718282 0.00000003
Unlock full access