Fortran high precision example

This is an example about the high precision in Fortran, at first we see a normal Program:

program hello
    implicit none
    real   :: div
    real   :: i
    Print  *,"write your number:"
    read   *, i
    i= div(i)
    print  *,"your result:",i
end program Hello

real function div( a )
  implicit none
  real  :: a
  div   = a/3
end function div

our Result looks like this:

 write your number:   
4      
 your result:   1.33333337

 

Now we use selected_real_kind(32) to get an higher precision data type:

program hello
    implicit none
    real(kind=selected_real_kind(32)):: div
    real(kind=selected_real_kind(32)) :: i
    Print  *,"write your number:"
    read   *, i
    i= div(i)
    print  *,"your result:",i
end program Hello

real(kind=selected_real_kind(32)) function div( a )
  implicit none
  real(kind=selected_real_kind(32))  :: a
  div   = a/3
end function div

Now we get this result:

 write your number:   
4   
 your result:   1.33333333333333333333333333333333327

looks much better than the first.

Fortran function example

This is an example in Fortran how to make a function:

program hello
    implicit none
    integer:: square
    integer:: i
    Print  *,"write your number:"
    read   *, i
    print  *,"your number:",i
    i= square(i)
    print  *,"your result:",i
end program Hello

integer function square( a )
  implicit none
  integer  :: a
  square   = a*a
end function square

Result:

 write your number: 
4   
 your number:           4  
 your result:          16