if( !require('phaseR') ){ install.packages('phaseR') } library(phaseR) source('../Chapter3/utils.R') ## Parameters: ## a = 1 alpha = 0.5 c = 0.75 gamma = 0.25 x_bar_linear = c/gamma # the linear approximation average y_bar_linear = a/alpha my_yprime = function(t, y, parameters){ xt = y[1] yt = y[2] dy = rep(NA, length(y)) dy[1] = a*xt - alpha*xt*yt dy[2] = -c*yt + gamma*xt*yt list(dy) } # Parts (b): # ts = seq(0, 10, length.out=500) res = ode(y=c(5, 2), times=ts, fun=my_yprime, parms=list()) # guess the initial conditions the book uses for its plot xs = res[, 2] # the numerical function x(t) ys = res[, 3] # the numerical function y(t) T = my_period(ts, xs-mean(xs)) T_linear = 2*pi/sqrt(a*c) print(sprintf('T_linear= %f; T= %f', T_linear, T)) my_trapezoidal = function(ts, ys){ ## ## A poor i.e. quick numerical implementation of a quadrature routine ## n = length(ys) delta_t = mean(diff(ts)) # expect the "x" grid to be uniform area = ( ys[1] + 2 * sum(ys[2:(n-1)]) + ys[n] ) * delta_t / 2 return(area) } mask = ts