1

The variable type in a do-loop in Fortran is an integer by default. However, I require to tabulate and plot the values of a function where the argument takes floating values. But I could not get an idea about how to write the code for the same. In C/C++, the for-loop could take floating-type argument.

The function that I need to plot is the following:

function

Here, 'a' is a parameter and the step size needs to be chosen as 0.0001.

Ian Bush
  • 6,996
  • 1
  • 21
  • 27
Richard
  • 155
  • 6

1 Answers1

4

Here are a couple of possible ways. Note that just because you can use a real for loop variable doesn't mean you should - there are good reasons why this is one of the very few things to be removed from the Fortran language! The example kind of shows why, compare the outputs of the two methods

ian-standard@barleybarber ~
$ cat inc.f90
Program inc

  Implicit None

  Real :: a
  Real :: a_lo, a_hi
  Real :: da

  Integer :: n_points
  Integer :: i

  Write( *, * ) 'a hi?'
  Read ( *, * )  a_hi
  Write( *, * ) 'a lo?'
  Read ( *, * )  a_lo
  Write( *, * ) 'da?'
  Read ( *, * )  da

  n_points = Int( ( a_hi - a_lo ) / da )

  ! First way - parallelisable
  Write( *, * ) 'First way'
  Do i = 0, n_points
     a = a_lo + Real( i ) * da
     Write( *, * ) a
  End Do

  ! Second way - not parallelisable
  Write( *, * ) 'Second way'
  a = a_lo
  Do While( a <= a_hi )
     Write( *, * ) a
     a = a + da
  End Do


End Program inc

ian-standard@barleybarber ~
$ gfortran -std=f2003 -Wall -Wextra -fcheck=all -O -g inc.f90 -o inc

ian-standard@barleybarber ~
$ ./inc
 a hi?
1
 a lo?
0
 da?
0.1
 First way
   0.00000000
  0.100000001
  0.200000003
  0.300000012
  0.400000006
  0.500000000
  0.600000024
  0.699999988
  0.800000012
  0.900000036
   1.00000000
 Second way
   0.00000000
  0.100000001
  0.200000003
  0.300000012
  0.400000006
  0.500000000
  0.600000024
  0.700000048
  0.800000072
  0.900000095
Ian Bush
  • 6,996
  • 1
  • 21
  • 27
  • 1
    For some additional info see answer in [post](https://stackoverflow.com/questions/30707668/fortran-do-loop-warning-to-use-integer-only) – jcerar Feb 25 '20 at 06:41