viernes, 25 de marzo de 2011

Derivada centrada

Subo este método de derivación puesto que es el mas optimo. Como veréis lo subo de dos formas distintas, elegid la que os parezca mas cómoda. Como veréis incluye la segunda derivada.
Programa Principal:

program main
use funcion
use numerico
use segunda_deriv
implicit none
real::x,h,DERI,DERI2
integer::n,m
write(*,*)'¿en que punto hacemos la derivada?'
read(*,*)x
h=1
write(*,*)'¿cuantas veces repetimos la 1º derivada?'
read(*,*)n
write(*,*)'¿cuantas veces repetimos la 2º derivada?'
read(*,*)m


call derivada(f1,x,h,n,DERI)
write(*,*)'la primera derivada es:'
write(*,*)DERI


call segunda_derivada(f1,x,h,m,DERI2)
write(*,*)'la segunda derivada es:'
write(*,*)DERI2


end program main



Module Numerico1:

module numerico
contains


subroutine derivada(f,x,h,n,DER)
interface
function f(x)
real,intent(in)::x
real::f
end function
end interface
real,intent(inout)::x,h
integer,intent(in)::n
real,intent(out)::DER
integer::i


do i=1,n
  DER=((f(x+h)-f(x-h))/(2*h))
  h=h/10
  write(*,*)h,DER
end do


end subroutine derivada
end module numerico


Module Numerico2:

module segunda_deriv
contains


subroutine segunda_derivada(f3,x,h,n,DER2)
interface
function f3(x)
real,intent(in)::x
real::f3
end function
end interface
real,intent(inout)::x,h
integer,intent(in)::n
real,intent(out)::DER2
integer::i


do i=1,n
  DER2=((f3(x+h)-2*f3(x)+f3(x-h))/(h*h))
  h=h/10
  if(DER2==0.0)then
    h=0.01
    DER2=((f3(x+h)-2*f3(x)+f3(x-h))/(h*h))
    exit
    end if
  write(*,*)h,DER2
end do


end subroutine segunda_derivada
end module segunda_deriv


Module funciones:

module funcion
contains


function f1(x)
real,intent(in)::x
real::f1
f1=(x**4)+(3*(X**2))-(5*x)
end function
end module funcion
...........................................................................................
Programa Principal 2:

program main
use funcion
use derivada
real::x,h
write(*,*)'elige el punto de derivacion'
read(*,*)x
h=0.01
sol=Diff_centrada(f1,h,x)
write(*,*)sol

sol2=Diff_centrada2(f1,h,x)
write(*,*)sol2
end program
Module Numerico:
:module derivada
contains
function Diff_centrada(f,h,var)
interface
function f(x)
real,intent(in)::x
real::f
end function
end interface
real,intent(in)::h
real,intent(in)::var
real::Diff_centrada
Diff_centrada=((f(var+h)-f(var-h))/(2*h))
end function


function Diff_centrada2(f,h,var)
interface
function f(x)
real,intent(in)::x
real::f
end function
end interface
real,intent(in)::h
real,intent(in)::var
real::Diff_centrada2
Diff_centrada2=((f(var+h)-(2*f(var))+f(var-h))/(h*h))
end function
end module derivada
Module Funciones:

module funcion
contains

function f1(x)
real,intent(in)::x
real::f1
f1=(x)**2
end function
end module funcion






2 comentarios: