# EDO: método de Euler.
# Limpando a memória
rm(list=ls(all=TRUE))
#-----------------------------------------------
RungK1<-function(f,u0,a,b,n){ # O método Euler
h=(b-a)/n
t=seq(a,b,by=h)
m=length(u0)
Y=matrix(0,m,n+1)
Y[,1]=u0
for (i in 1:n){ Y[,i+1]=Y[,i]+h*f(t[i],Y[,i]) }
return(Y)
}
#----------Aplicação na Equação do pendulo simples
f<-function(s,U){ # Definicao de f(t,Y)=Y'.
u=U[1]; v=U[2]
return(c(v,-9.8*sin(u)))
}
a=0; b=1 # a é o tempo inicial e b o tempo final
u0=c(pi/6,0) # condição inicial, posição do pendulo em radianos e velocidade inial em m/s
#--- Primeira simulação para estimar Y(1).
n=10
Y=RungK1(f,u0,a,b,n); print("Estimativa com n=10");Y[,n+1]
h=(b-a)/n
t=seq(a,b,by=h)
plot(t,Y[1,],'l',col = "blue",ylim=c(-1,1),ylab=expression(paste(theta,"(t)")))
par(new=TRUE)
#--- Segunda simulação para estimar Y(1).
n=100
V=RungK1(f,u0,a,b,n); print("Estimativa com n=100");V[,n+1]
h=(b-a)/n
t=seq(a,b,by=h)
plot(t,V[1,],'l',col = "green",ylab='',ylim=c(-1,1))
par(new=TRUE)
#--- Terceira simulação para estimar Y(1).
n=1000
V=RungK1(f,u0,a,b,n); print("Estimativa com n=1000");V[,n+1]
h=(b-a)/n
t=seq(a,b,by=h)
plot(t,V[1,],'l',col = "red",ylab='',ylim=c(-1,1))
par(new=TRUE)
#--- Quarta simulação para estimar Y(1).
n=10000
V=RungK1(f,u0,a,b,n); print("Estimativa com n=10000");V[,n+1]
h=(b-a)/n
t=seq(a,b,by=h)
plot(t,V[1,],'l',col = "purple",ylab='',ylim=c(-1,1))
legend(0.75,1, legend=c("n=10", "n=100","n=1000","n=10000"),
col=c("blue", "green","red","purple"), lty=1:1:1:1, cex=0.8)
To embed this project on your website, copy the following code and paste it into your website's HTML: