########################
# R Course WS 2019-20
########################
# Solutions to Exercise sheet 2 - Getting started with R
# Author: Noémie Becker
# Last update: 2020-02-17
### Exercise 2 - Using R as a calculator
4^5
choose(23, 12)
factorial(9)
sqrt(pi)
### Exercise 3 - sum() and prod()
# Note that it is convenient - even if not necessary - to define the vector i in
# each case
i <- (30:200)
sum(i)
# This also works
sum(30:200)
i <- (1:100)
sum(1/i)
# This also works, but here you might already see why it is convenient to define
# i before - you can read it better this way
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 meaning that the value is too big to be shown
### Exercise 4 - Getting help
# Using the help pages
?signif()
?exp()
?expm1(x)
# 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
exp(x_i)-1
# RESULT 1 (as given by R)
# [1] 1.005017e-02 1.000500e-03 1.000050e-04 1.000005e-05 1.000000e-06
# [6] 1.000000e-07 1.000000e-08 1.000000e-09 1.000000e-10 1.000000e-11
# [11] 1.000089e-12 9.992007e-14 9.992007e-15 1.110223e-15 0.000000e+00
# [16] 0.000000e+00 0.000000e+00
expm1(x_i)
# RESULT 2 (as given by R)
# [1] 1.005017e-02 1.000500e-03 1.000050e-04 1.000005e-05 1.000001e-06
# [6] 1.000000e-07 1.000000e-08 1.000000e-09 1.000000e-10 1.000000e-11
# [11] 1.000000e-12 1.000000e-13 1.000000e-14 1.000000e-15 1.000000e-16
# [16] 1.000000e-17 1.000000e-18
# Which result do you trust more?
# From the help page you know:
# ‘exp’ computes the exponential function
# ‘expm1(x)’ computes exp(x) - 1 accurately also for |x| << 1
# You see that with the function exp() (RESULT 1) 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() (RESULT 2) 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.