Cosas de la práctica N° 1 ## ejercicio 2 f <- function(t,x){ return ((x-5)*((cos(t))^2-0.5)) } n <- 10/0.01 h <- 0.01 t <- 0 xeul <- 0 for(i in c(1:n)){ t[i+1] <- t[i]+h xeul[i+1] <- xeul[i] + h * f(t[i],xeul[i]) } plot(t,xeul,ylim=c(-2,10),col="green",type="l") for (k in c(1:10)) { t[1] <- 0 xeul[1] <- k for(i in c(1:n)){ t[i+1] <- t[i]+h xeul[i+1] <- xeul[i] + h* f(t[i],xeul[i]) } lines(t,xeul,col="blue") } ########################################################## ## ejercicio 4 euler1 <- function(f,t0,tf,h,y0) { n <- (tf-t0)/h t <- t0 y <- y0 for(i in 1:n) { y0 <- y0 + h * f(t0, y0) t0 <- t0 + h t <- c(t, t0) y <- c(y, y0) } return(data.frame(t = t, y = y)) } t <- 0 y <- 0 euler2 <-function(f,t0,tf,h,y0){ n<-(tf-t0)/h t[1]<-t0 y[1]<-y0 i=1 while(i<=n){ t[i+1]<-t[i]+h y[i+1]<-y[i]+h*f(t[i],y[i]) i<-i+1 } return(data.frame(t,y)) } #Ejemplo 1 f1<-function(t,y){ return((y-5)*((cos(t))^2-0.5)) } e1<-euler1(f1,0,10,0.25,0) show(e1) plot(e1[,1],e1[,2],ylim=c(-5,5),type = "l", col="red") e2<-euler2(f1,0,10,0.25,0) show(e2) plot(e2[,1],e1[,2],ylim=c(-5,5),type = "l", col="green") #################################################### ## ejercicio 6 f<-function(t,y,k){ return(k*y) } t <- 0 y <- 0 euler <-function(f,t0,tf,h,y0,k){ n<-(tf-t0)/h t[1]<-t0 y[1]<-y0 i=1 while(i<=n){ t[i+1]<-t[i]+h y[i+1]<-y[i]+h*f(t[i],y[i],k) i<-i+1 } return(data.frame(t,y)) } eulerimp <-function(t0,tf,h,y0,k){ n<-(tf-t0)/h t[1]<-t0 y[1]<-y0 i=1 while(i<=n){ t[i+1]<-t[i]+h y[i+1]<-(1/(1-h*k))*y[i] i<-i+1 } return(data.frame(t,y)) } e1<-euler(f,0,1,0.01,1,1) e1otro<-eulerimp(0,1,0.01,1,1) plot(e1[,1],e1[,2],ylim=c(1,3),type = "l", col="red") lines(e1otro[,1],e1otro[,2], col="green") curve(exp,0,1,n=1001,col="blue",add=TRUE) e10<-euler(f,0,1,0.01,1,10) e10otro<-eulerimp(0,1,0.01,1,10) plot(e10[,1],e10[,2],ylim=c(0,2000),type = "l", col="red") curve(exp(10*x),0,1,n=1001,col="blue",add=TRUE) lines(e10otro[,1],e10otro[,2], col="green") ############################################################# ## ejercicio 8 # limpiar variables rm(list=ls()) # datos iniciales t0 <- 0 x0 <- 0.5 # función de la EDO f <- function(t,x){ x^2 } # tiempo final de la aproximación T <- 2.1 # número de pasos y tamaño del paso n <- 10 h <- (T-t0)/n # método de Euler t <- t0 xeul <- x0 for(i in c(1:n)){ t[i+1] <- t[i]+h xeul[i+1] <- xeul[i] + h* f(t[i],xeul[i]) } # método de Euler con paso adaptado lambda <- 0.1 hmin <- 0.001 tad <- t0 xeulad <- x0 c <- f(t0,x0) i <- 1 while(lambda/hmin >= c[i] ) { xeulad[i+1]<- xeulad[i]+lambda tad[i+1] <- tad[i]+lambda/f(tad[i],xeulad[i]) c[i+1] <- f(tad[i+1],xeulad[i+1]) i <- i+1 } # graficar plot(t,xeul, ylim=c(0,200),type = "l", col="red") lines(tad,xeulad,col="green") curve(1/(2-x),0,2,n=100001,col="blue",add=TRUE)