Example R programs and commands 2. Numerical integration; Fourier transform # # Everything between "#" and the end of a line is a comment. # ###### INTEGRATE A FUNCTION ALREADY KNOWN TO R integrate(sin, 0,pi) # interval is [0,pi] ###### INTEGRATE A USER-DEFINED FUNCTION f <- function(x){return(exp(-x*x/2)/sqrt(2*pi) )} # standard normal density integrate(f, -1,1) integrate(f, -1.96,1.96) ###### DISCRETE FOURIER TRANSFORM N<-1024 # Large for visualization, power of 2 for speed t<- 2*pi*(0:(N-1))/N # N points in [0,2*pi) plot(t,sin(t),type="l") # Trigonometric function plot matplot(t,cbind(cos(t),sin(t)), type="l") # Two plots on same axes # Make a vector of complex numbers: freq<-5; f<-complex(N, real=cos(freq*t), imaginary=sin(freq*t)) matplot(t,cbind(Re(f),Im(f)), type="l") # ...and plot Re and Im parts Tf <- fft(f) # Discrete ("fast") Fourier transform matplot(cbind(Re(Tf),Im(Tf)), type="l") # ...plot Re and Im parts of FFT # Another example of the FFT: freq<-50; f<-complex(N, real=cos(freq*t), imaginary=sin(freq*t)) matplot(t,cbind(Re(f),Im(f)), type="l") Tf <- fft(f) matplot(cbind(Re(Tf),Im(Tf)), type="l")