---
title: "Solutions to exercise sheet 2 - Getting started with R"
author: Sonja Grath
output: pdf_document
fontsize: 11pt
---

## Exercise 2 - Using R as a calculator

```{r}
4^5
choose(23, 12)
factorial(9)
sqrt(pi)
```

## Exercise 3 - sum() and prod()

```{r}
# It works directly with sum()
sum(30:200)
# It is convenient - even if not necessary - to define the vector i before:
i <- (30:200)
sum(i)

i <- (1:100)
sum(1/i)
# or
sum(1/(1:100))

i <- (0:100)
sum(i*exp(-i))
# or
sum((0:100)*exp(-(0:100)))

i <- (1:100)
prod(2*i^2-i)
# or
prod(2*(1:100)^2-(1:100))
# The answer from R is Inf (Infinity) meaning that the value is too big to be shown.
```

## Exercise 4 - Getting help

```{r}
# Using the help pages
?signif()
?exp()
?expm1(x)
``` 

```{r}
# Vector which contains each element of the vector (1:100)^8 rounded to 3 
# significant digits
signif(((1:100)^8), digits = 3)
# Define the vector x_i
x_i <- 10^(-2:-18)
# Use exp() and expm1() as specified in the help pages
result1 <- exp(x_i)-1
result1
result2 <- expm1(x_i)
result2
``` 

### Which result do you trust more?

From the help page you know:

- *exp(x)* computes the exponential function for x
- *expm1(x)* computes *exp(x) - 1* accurately also for |x| << 1

You see that with the function *exp()* (*result1*) the values start to get inaccurate with e to the power of $10^{-11}$, the last 3 values are even given as 0 already. 
In contrast, for *expm1()* (*result2*) you have accurate values even for these small values. So, you would probably trust the *expm1()* function more if you have to deal with very small values.

```{r}
sessionInfo()
``` 

Last update: `r as.Date(Sys.time())`