0

I wrote this simple code. I obtain Q_in and Q_fin but the value of Q remains zero. So I think that the do loop doesn't work.

  program readwrite
  implicit none
  real a(200,4),Q_in,Q_fin,Q,Q_tot,v_med
  integer i,j,nj

  character*40 nome

  write(6,*) 'nome file'
  read(5,'(a)') nome
  open(unit=16,file=nome)

  nj=180

  do i=1,nj
  read(16,*) (a(i,j),j=1,4)
  enddo

        Q_in=(a(1,1)-a(1,3))/2*a(1,2)
        Q_fin=(2-a(180,1))/2*a(180,2)

  Q=0

  do i=1,nj-1

  Q=Q+1/2*((a(i+1,2)+a(i,2))*(a(i+1,1)-a(i,1)))

  enddo

        Q_tot=Q+Q_in+Q_fin

        v_med=Q_tot/2


   write(6,*) 'velocita media', v_med
     write(6,*) 'Q', Q
   write(6,*) 'Q_in', Q_in
   write(6,*) 'Q_fin', Q_fin
        end

1 Answers1

2

Your error is in:

Q=Q+1/2*((a(i+1,2)+a(i,2))*(a(i+1,1)-a(i,1)))

The 1/2 is integer arithmetic and returns 0, then you multiply by the rest, still summing 0 for all iterations. Just change it to a real value 0.5

Q=Q+0.5*((a(i+1,2)+a(i,2))*(a(i+1,1)-a(i,1)))

Also, you could use array operations instead of the explicit do. Maybe this gives the compiler more chance to optimize (run and compare both approaches). You'd remove the whole do I=1, nj-1 (...) end do block and substitute by this:

Q = 0.5 * sum((a(2:nj, 2) + a(:nj-1, 2)) * (a(2:nj, 1) - a(:nj-1, 1)))

There is probably a better version with dot_product, but I'll let this as an exercise.

kvantour
  • 25,269
  • 4
  • 47
  • 72
Rodrigo Rodrigues
  • 7,545
  • 1
  • 24
  • 36