# Gráfico em 3 dimensões

# Resolver a equação f(x,y)=(f1(x,y),f2(x,y))=(0,0).

f1<-function(u){   # Definição de f1
r=u[1]
s=u[2]
return(exp(r+s)-2)
}

x <- seq(-0.5,2, by=0.05)
y <- seq(-0.5,2,by=0.05)
mf1<-function(r,s){u=c(r,s); f1(u)}# auxiliar para gráfico
z=matrix(0,length(x),length(y))
for ( i in 1:length(x)){
for ( j in 1:length(y)){z[i,j]=f1(c(x[i],y[j]))}}


require(grDevices) # for trans3d
persp(x, y, z, theta = 30, phi = 40, expand = 1)
contour(x,y,z,level=0,col="red")
par(new=TRUE)

f2<-function(u){   # Definição de f2
r=u[1]
s=u[2]
p=sin(r)+cos(s)-1
return(p)
}

zz=matrix(0,length(x),length(y))
for ( i in 1:length(x)){
for ( j in 1:length(y)){zz[i,j]=f2(c(x[i],y[j]))}}

contour(x,y,zz,level=0,col="blue")

legend(2,3.5, legend=c("f1(u)", "f2(u)"),
       col=c("red","blue"), lty=c(1,1), cex=0.8)

persp(x, y, zz, theta = 30, phi = 40, expand = 1)

f<-function(u){c(f1(u),f2(u))}

mf<-function(u){   # Definição de mf=|f|^2/2; com coordenadas para gráfico
(f1(u)^2+f2(u)^2 )/2
}

Jacf<-function(u){ # Jacobiano de f(x,y) aproximado
h=10^(-5)
v=u; v[1]=u[1]+h; v1=u; v1[1]=u[1]-h; 
dfx= f(v)-f(v1)
v=u; v[2]=u[2]+h; v1=u; v1[2]=u[2]-h; 
dfy= f(v)-f(v1)
J=matrix(0,2,2)
J[1,]=dfx; J[2,]=dfy
return(J/(2*h))
} 

#--------------------- Método de Euler para resolver a equação u'(t)=-grad mf(u(t)).

t0=0  # tempo inicial
e0=c(0,0) # condição inicial 
n=50

tt=0:n; hh=0*tt
Y=matrix(0,2,length(tt))
Y[,1]=e0

for ( i in 1:(length(tt)-1)){
w=t(Jacf(Y[,i]))%*%f(Y[,i])
bb=abs( sum( ( t( (Jacf(Y[,i]) )%*%Jacf(Y[,i]))%*%w )*w ) )
h=sum(w*w)/bb
if (bb!=0){Y[,i+1]=Y[,i]-h*w
    hh[i]=h
}
tt[i+1]=tt[i]+h
}

print("Ponto de minimo de f(z) ou raiz de p(z)"); Y[,length(tt)]
print("Valor minimo aproximado"); mf(Y[,length(tt)])

plot(Y[1,],Y[2,],'l',col="blue")

mY=0*tt
for ( i in 1:length(tt)){mY[i]=mf(Y[,i])}

plot(tt,mY,'l', col = "blue")


plot(tt,hh,'l', col = "green")

Embed on website

To embed this project on your website, copy the following code and paste it into your website's HTML: