Está en la página 1de 16

FORTRAN POWERSTATION 90

EJEMPLO 1: SUMA DE ENTEROS Y REALES Y VISUALIZA

program ejemplo
implicit none
integer::a,b,c
real::e,f,g
a=2
b=3
c=a+b
e=1.5
f=2.5
g=e+f
print *, "hola, suma:",c,g
pause
end program

( Después compilar: Build…compile Text1.f190


Después construir el ejecutante: Build….build Text1.exe
Después ejecutar: Build….Execute…Text1.exe )

EJEMPLO 2: LEE Y ESCRIBE VARIABLES, QUE SON UN CONJUNTO DE CARACTERES


(LETRAS Y ESPACIOS).

program ejemplo
implicit none
integer::a,b,c
real::e,f,g
character(len=10)::elmer
character(5)::elmer1
character(10)::elmer2(3),nomb(2)

write(*,*)"escribir 3 nombres"

read(*,*)elmer
read(*,*)elmer1
read(*,*)elmer2
read(*,*)nomb
a=2
b=3
c=a+b
e=1.5
f=2.5
g=e+f
print *, "hola, suma:",c,g
pause
write(*,*)"los nombres son escritos"
write(*,*)elmer
write(*,*)elmer1
write(*,*)elmer2
write(*,*)nomb
end program

EJEMPLO3: CALCULA LA FACTORIAL DE UN NÚMERO. EL IF()

program ejemplo
implicit none
integer::cont,fact, num
write(*,*)"ingresa un numero"
read(*,*)num
cont=1
fact=1
10 if(cont<=num) then
fact=fact*cont
cont=cont+1
goto 10
end if
write(*,*)"el factorial es",fact
pause
end program

EJEMPLO4: CALCULA LA FACTORIAL DE UN NÚMERO. EL DO X=1, VALOR MAX,


INCREMENTO

program ejemplo
implicit none
integer::cont,fact, num
write(*,*)"ingresa un numero"
read(*,*)num
fact=1
do cont=1,num,1
fact=fact*cont
end do
write(*,*)"el factorial es",fact
pause
end program

EJEMPLO 5: CALCULA LA FACTORIAL DE UN NÚMERO, DO WHILE.


program ejemplo
implicit none
integer::cont,fact, num
write(*,*)"ingresa un numero"
read(*,*)num
cont=1
fact=1
do while(cont<=num)
fact=fact*cont
cont=cont+1
end do
write(*,*)"el factorial es",fact
pause
end program

EJEMPLO 6: LEE Y ESCRIBE UNA VARIABLE (UN NOMBRE)

program ejemplo
implicit none
! My first Fortran 90 program!
! Greetings!
character NAME*10
print*, 'What is your name?'
read*, NAME
print*, 'Hi there, ', NAME
end program

EJEMPLO 7: MOVIMIENTO VERTICAL ASCENDENTE


program MVA
! movimiento vertical ascendente
implicit none
real, parameter :: g = 9.81 ! acceleration due to gravity ¡declara g como parametro
real s,so ! desplazamiento (m)
real ts ! tiempo
real t ! tiempo
real vo ! velocidad inicial (m/s)
print*, "Movimiento vertical ascendente"
print*, 'posicion inicial, m'
read*,so
print*, 'velocidad inicial, m/s'
read*,vo
print*
ts = vo / g
print*, "tiempo de subida, ts, en seg"
print*,ts
print*
print*, 'Entrar un tiempo menor al ts, en seg'
read*,t
print*
print*, 'Posicion final, m'
print*
s = so + vo * t - g / 2 * t ** 2
print*, s
end program

EJEMPLO 8: RAÍZ CUADRADA DE UN NUMERO CON NEWTON


1. Input a
2. Initialize x to 1
3. Repeat 6 times (say)
Replace x by (x + a/x)/2
Print x
4. Stop.

program Newton
! Square rooting with Newton
implicit none
real A ! number to be square rooted
integer I ! iteration counter
real X ! approximate square root of A
write( *, 10, ADVANCE = 'NO' ) ' Enter number to be square rooted: '
10 format( A )
¡Permite la entrada del dato en la misma línea del aviso
read*, A
print*
X=1 ! initial guess (why not?)
do I = 1, 6
X = (X + A / X) / 2
print*, X
end do
print*
print*, 'Fortran 90''s value:', sqrt( A ) ¡es el valor que calcula el programa fortran 90
end

EJEMPLO 9: MOVIMIENTO COMPUESTO

program Proyectil
implicit none

real, parameter :: g = 9.81


real, parameter :: pi = 3.1415927
real A
real T
real Theta
real U
real V
real Vx
real Vy
real X
real Y
read*, A,T,U
A = A * Pi / 180 ! convert angle to radians
X = U * cos( A ) * T
Y = U * sin( A ) * T - g * T * T / 2.
Vx = U * cos( A )
Vy = U * sin( A ) - g * T
V = sqrt( Vx * Vx + Vy * Vy )
Theta = atan( Vy / Vx ) * 180 / Pi
print*, 'x: ', X, ' y: ', Y
print*, 'V: ', V, ' Theta: ', Theta
end

EJEMPLO 10: VER DATO Y LA HORA

program test_time_and_date
character(10) :: date
character(15) :: time
character(15) :: hora
!integer,dimension(8) :: values
! using keyword arguments
call date_and_time(date,time) ¡ llama dato y tiempo
print*, date
print*, time

hora = time(1:2) // ':' // time(3:4) // ':' // time(5:10)


print*, hora
end program

EJEMPLO 11: SOLUCIONES NO COMPLEJAS DE LA ECUACIÓN CUADRÁTICA


Flujo de diagrama
program EQ2
implicit none
real a, b, c, x, x1, x2

print*,'entrar a'
read*,a
print*,'entrar b'
read*,b
print*,'entrar c'
read*,c

if (a==0) then
if (b==0) then
if (c==0) then
print*,'solucion indeterminada'
else
print*,'No hay solucion'
end if
else
x=-c/b
print*,'Unicamente una raiz, es lineal la ecuacion',x
end if

else if (b*b < 4*a*c) then


print*,'Raices complejas'

else if (b*b == 4*a*c) then


x = - b / (2*a)
print*,'Raices iguales', x

else
x1 = (-b + sqrt(b*b - 4*a*c)) / (2*a)

x2 = (-b - sqrt(b*b - 4*a*c)) / (2*a)

print*,'Las raices son:', x1, x2

end if
end program

EJEMPLO 12: SOLUCION REAL Y COMPLEJA DE LA ECUACIÓN CUADRÁTICA

program EQ2
implicit none

real a, b, c
real discriminante
real parte_real, parte_imag
real x1, x2
write(*,*) "Entrar los coeficientes cuadratica"
read(*,*) a, b, c
discriminante = b**2 - 4 * a * c

if (discriminante > 0) then

x1 = ( -b + sqrt(discriminante) ) / (2 * a )
x2 = ( -b - sqrt(discriminante) ) / ( 2 * a )

write(*,*) "Esta ecuacion tiene dos raices reales:"


write(*,*) "X1:",x1
write(*,*) "X2:",x2

else if (discriminante == 0) then

x1 = ( -b ) / ( 2 * a )
write (*,*) 'Esta ecuacion tiene dos raices reales:'
write (*, *) 'XI = X2 = ', x1

else
parte_real = ( -b ) / ( 2 * a )
parte_imag = sqrt (abs(discriminante)) / (2 * a)

write(*,*) "Esta ecuacion tiene dos raices complejas:"

write (*,*) 'X1 = ', parte_real, ' +i ', parte_imag


write (*,*) 'X2 = ', parte_real, ' -i ', parte_imag
end if
pause
end program

EJEMPLO 13: Evaluar una función f(x,y)


program funxy
implicit none
real x, y
real fun
write(*,*) "Entrar los coeficientes de x y y:"
read(*,*) x, y

if ( ( x >= 0. ) .AND. ( y >= 0. ) ) then


fun = x + y
else if ( ( x >= 0. ) .AND. ( y < 0. ) ) then
fun = x + y**2
else if ( ( x < 0. ) .AND. ( y >= 0. ) ) then
fun = x**2 + y
else
fun = x**2 + y**2
end if

write(*,*) 'El valor de la funcion es: ', fun

end program

EJEMPLO 14: Movimiento vertical de una partícula ascendente.


! movimiento vertical ascendente
program MVA
implicit none

real, parameter :: g = 9.81 ¡declara g como parametro


real y,yo, Hmax ! desplazamiento (m)
real t, ts, tv ! tiempo
real vo, v ! velocidad (m/s)

print*, "Movimiento vertical ascendente"


print*
print*, "+y hacia arriba, y = 0 en Tierra"
print*
print*, 'posicion inicial de lanzamiento, m'
read*,yo
print*, 'velocidad inicial, m/s'
read*,vo
print*, 'Ingresar el tiempo en seg'
read*,t
print*

v = vo - g*t
ts = vo / g
tv = (vo + sqrt(vo**2 + 2*g*yo)) / g
Hmax = (vo ** 2) / (2*g)

if ( (t < 0 ) ) then
print*, 'No exite tiempo negativo'
stop

else if ( vo < 0 ) then


print*, 'No exite'
stop

else if ( t > tv ) then

print*, 'No exite'


stop
else
y = yo + vo*t - g / 2 * t ** 2

end if

print*, 'Tiempo subida, seg'


print*, ts
print*, 'Tiempo de vuelo, seg'
print*, tv
print*, 'Elevacion maxima desde el lanzamiento, m'
print*, Hmax
print*, 'Posicion, m'
print*, y
print*, 'Velocidad, m/s'
print*,v

end program

EJEMPLO 15: Movimiento vertical de una partícula ascendente: write (), format ().
program MVA
implicit none

real, parameter :: g = 9.81 !declara g como parametro


real y,yo, Hmax ! desplazamiento (m)
real t, ts, tv ! tiempo
real vo, v ! velocidad inicial (m/s)

write(*,100)
100 format(' Estudiar el movimiento ascendente de una '&
'particula',/,' Hacia arriba es +y y y = 0 a Tierra',/,' Ingresar:')

write(*,110)
110 format(' 1--La posicion inicial, yo, m:')
read*, yo
write(*,120)
120 format(' 2--La velocidad inicial, vo, m/s:')
read*, vo
write(*,130)
130 format(' 3--El tiempo, t, seg:')
read*,t
v = vo - g*t
ts = vo / g
tv = (vo + sqrt(vo**2 + 2*g*yo)) / g
Hmax = (vo ** 2) / (2*g)

if ( (t < 0 ) ) then
print*, 'No exite tiempo negativo'
stop

else if ( vo < 0 ) then


print*, 'No exite'
stop

else if ( t > tv ) then

print*, 'No exite'


stop
else
y = yo + vo*t - g / 2 * t ** 2

end if

write(*,140) ts, tv, Hmax, y, v


140 format (' Resultados de:',/,&
' Tiempo subida = ', ES10.3,' seg',/,&
' Tiempo de vuelo = ', ES10.3,' seg',/,&
' Altura maxima desde yo = ', ES10.3,' m',/,&
' Posicion = ', ES10.3,' m',/,&
' Velocidad = 'ES10.3,' m/s')

end program

EJEMPLO 16: Ajuste de mínimos cuadrados de los datos de un archivo, por ejemplo,
“input.txt”
Se crea un archivo texto usando el block de notas, en su interior se encuentra los
pares de datos.

program MinimosCuadrados
implicit none

integer,parameter::lu = 18 !unidad I/O para disco I/O


character(24):: filename !nombre del archivo de entrada
integer:: ierror !bandera de estado de declaraciones I/O
integer:: n = 0 !Number of input data pairs (x,y)
real:: slope !Slope of the line
real:: sum_x = 0 !Sum of all input X values
real:: sum_x2 = 0 !Sum of all input X values squared
real:: sum_xy = 0 !Sum of all input X*Y values
real:: sum_y = 0 !Sum of all input Y values
real:: x
real:: x_bar !Average X value
real:: y
real:: y_bar
real:: y_int !Y-axis intercept of the line

write (*,1000)
1000 format (1X,'Este programa ejecuta un ajuste minimos cuadrados de un ',/, &
1X,'conjunto de datos ingresados a una linea recta. Entrar el nombre',/ &
1X,'del archivo que contiene la entrada de los pares (x,y): ' )

read (*,'(A)') filename

! Abre el archivo de entrada


open (UNIT=lu, FILE = filename, STATUS = 'OLD', ACTION = 'READ', &
IOSTAT = ierror)

!chequear para ver si fallo OPEN


errorcheck: if ( ierror > 0 ) Then
write (*,1020) filename
1020 format (1X,'ERROR: File ',A,'no existe!')
else

! Archivo abierto con exito. Leer los pares (x,y) desde


! el archivo de entrada.
do
read (lu,*,IOSTAT=ierror) x, y ! obtener apar
if ( ierror /= 0 ) exit
n=n+1
sum_x = sum_x + x
sum_y = sum_y + y ! Calculo estadistico
sum_x2 = sum_x2 + x**2
sum_xy = sum_xy + x*y
end do

!Calcular la pendiente y la interseccion


x_bar = sum_x / real(n)
y_bar = sum_y / real(n)
slope = (sum_xy - sum_x * y_bar) / ( sum_x2 - sum_x * x_bar)
y_int = y_bar - slope * x_bar

!Decir usuario
write (*, 1030 ) slope, y_int, n
1030 format ('0','Coeficientes de regresion para la linea de minimos cuadraticos:',&
/,1X,' slope (m) = ', F12.3, &
/,1X,' Intercept (b) = ', F12.3, &
/,1X,' No of points = ', I12 )

! Cerrar el archivo de entrada y quitar


close (UNIT=lu)
end if errorcheck
end program

EJEMPLO 17: Calcula la raíz cuadrada y cubica de 10 números: usando array()

program Raiz2_3
implicit none

integer, parameter:: tamano_max = 10

integer j
real, dimension(tamano_max):: valor
real, dimension(tamano_max):: raiz2
real, dimension(tamano_max):: raiz3

do j = 1, tamano_max
valor(j) = real(j)
raiz2(j) = sqrt(valor (j))
raiz3(j) = valor(j)**(1./3.)
end do

write (*,100)
100 format ('0',20X,'Tabla de las raices cuadradas y cubicas',/,&
4X,' Numero Raiz cuadrada Raiz cubica', &
3X,' Numero Raiz cuadrada Raiz cubica',/,&
4X,' ====== ============= ===========',&
3X,' ====== ============= ===========')
write (*,110) (valor(j), raiz2(j), raiz3(j), j = 1, tamano_max)
110 format (2(4X,F6.0,9X,F6.4,9X,F6.4))
end program

EJEMPLO 18: Consigue la raíz x3 + x - 3 = 0, por el método de Newton

program RaizNewton
implicit none

integer :: Its = 0 ! contador de interaccion


integer :: MaxIts = 20 ! interacciones máxima
logical :: Converged = .false. ! bandera de convergencia
real :: Eps = 1e-6 ! error maximo
real :: X = 2 ! iniciando
do while (.NOT. Converged .AND. Its < MaxIts)
X = X - F(X) / DF(X)
print*, X, F(X)
Its = Its + 1
Converged = abs( F(X) ) <= Eps
end do

if (Converged) then
print*, 'Newton converged'
else
print*, 'Newton diverged'
end if

contains
function F(X)
! problem is to solve f(x) = 0
real F, X
F = X ** 3 + X - 3
end function F
function DF(X)
! first derivative of f(x)
real DF, X
DF = 3 * X ** 2 + 1
end function DF

end program

EJEMPLO 19: Ordena los números en un archivo de entrada, ejemplo “input1.txt”:


array(), /= significa “distinto de” o “no igual a”.

program Ordenar
implicit none

integer, parameter:: max_size = 10

real, dimension(max_size):: a !matriz para ordenar


character(20) filename ! nombre de la entrada del archivo
integer i
integer iptr !Puntero para el valor más pequeño
integer j
integer:: nvals = 0 !Número de valores de datos para ordenar
integer status !Estado de E / S: 0 para el éxito
real temp !Variable temporal para intercambiar

! Get the name of the file containing the input data.


write (*,1000)
1000 format (1X,' Ingrese el nombre del archivo con los datos para ordenar: ')
read (*,'(A20)') filename

! Abrir el archivo de datos de entrada. El estado es OLD porque los datos de entrada deben
! ya existir
open ( UNIT=9, FILE=filename, STATUS='OLD', ACTION='READ', &
IOSTAT=status )

! ¿Fue exitoso el OPEN?

fileopen: if ( status == 0) then

! El archivo se abrió correctamente, así que lea los datos para ordenar
! a partir de él, clasifique los datos y escriba los resultados.
! Primera lectura en datos.

do
read (9, *, IOSTAT=status) temp ! Obtener valor
if ( status /= 0 ) exit ! Salida al final de los datos
nvals = nvals + 1 ! Recuento de cuentas
a(nvals) = temp !guardar valor en matriz
end do

! Ahora, ordena los datos,


outer: do i = 1, nvals-1

! Encuentre el valor mínimo en a (i) a través de a (nvals)

iptr = i
inner: do j = i+1, nvals
minval: if ( a(j) < a(iptr) ) then
iptr = j
end if minval
end do inner

! iptr ahora apunta al valor mínimo, así que cambie a (iptr) con
! a (i) si i / = iptr.

swap: if ( i /= iptr ) then


temp = a(i)
a(i) = a(iptr)
a(iptr) = temp
end if swap
end do outer

! Ahora escriba los datos ordenados.

write(*,'(1X,A)') 'The sorted output data values are: '


write(*,'(4X,F10.4)') ( a(i), i = 1, nvals)

else fileopen

! Otro archivo abierto falló. Dile al usuario.


write (*,1050) status
1050 format (1X,'File open faile - - status = ', I6)
end if fileopen
end program

EJEMPLO 20:

También podría gustarte