{### Euler's Method ###

library(phaseR)
library(readxl)

# Specify beginning and ending times and step size
# to create sequence of time values
# We'll create two different sequences for comparison of step sizes,
# but in general can just change 'by' and rerun script
ss <- 10
ss2 <- 1
t <- seq(0, 200, by = ss)
t2 <- seq(0, 200, by = ss2)

# Specify initial condition
x0 <- 3.93
r<- 0.03
K<- 251.86

# Function to be integrated (right-hand expression of the derivative above)
ex <- function(x){r*x*(1-(x/K))}

# Create empty vector to store results; put initial condition in first position
# Again, we'll create two vectors for comparison
x <- c()
x[1] <- x0
x2 <- c()
x2[1] <- x0

# This loop implements the Euler's Method algorithm
# Loop over time, approximating function at each time step
for (i in 1:(length(t)-1)){
  x[i+1] = x[i] + ss * ex(x[i])
}
for (i in 1:(length(t2)-1)){
  x2[i+1] = x2[i] + ss2 * ex(x2[i])
}

# Produce a table of output
data.frame(setNames(t, x))
data.frame(setNames(t2, x2))

# Plot approximation, using bullet points at each approximated value
plot(x~t, type="l", col = "blue")
points(t, x, pch = 20, col = "blue")

# Add actual solution to graph
curve(989.5 / (247.85*exp(-.03*x)+3.93), add=T)

# Add other approximation to graph, 
# using bullet points at each approximated value
# and connecting them with line segments
points(t2, x2, pch = 20, col = "red")
lines(t2, x2, pch = 20, col = "red")
 echo(false)}