José Osorio
José Osorio

Reputation: 115

Avoid making too many nested loops

I'm trying to calculate the integer solutions of this equation:

ax + by + cz = d for x, y, z

with |ax + by + cz - d| < epsilon

so I'm trying 1 by 1 the solutions with "DO" like this

DO i1=1,max
DO i2=1,max
DO i=1,max
aux=abs(&
 d(1)*tazasmin(1)*i1+d(2)*tazasmin(2)*i2+&
 d(3)*tazasmin(3)*i3+d(4)*tazasmin(4)*i4+d(5)*tazasmin(5)*i5+&
 d(6)*tazasmin(6)*i6 &
+d(7)*tazasmin(7)*i7+d(8)*tazasmin(8)*i8+d(9)*tazasmin(9)*i9&
+d(10)*tazasmin(10)*i10+d(11)*tazasmin(11)*i11+d(12)*tazasmin(12)*i12 &
+d(13)*tazasmin(13)*i13+d(14)*tazasmin(14)*i14&
+d(15)*tazasmin(15)*i15+d(16)*tazasmin(16)*i16-tse)    
    IF (aux<=epsilon) THEN
       //save the solutions.
    END IF
END DO
END DO
END DO

I know how to fix the long equation part (to make it elegant and beautiful), but is there a way to avoid the excessive use of DO?

Upvotes: 1

Views: 116

Answers (1)

agentp
agentp

Reputation: 6999

I'm guessing you really want to loop over all 16 values.. try something like this:

  implicit none
  integer,parameter  :: nvar = 4
  integer, parameter :: max = 3
  integer varray(nvar)
  integer c,k
  do c=1,max**nvar
     do k=1,nvar            
        varray(k)=mod((c-1)/max**(nvar-k),max)+1
     enddo
! now your expresion is like:
     aux=abs(total(d*tazasmin*varray))
! assuming d and tazasmin are apporpriately declared arrays        
  enddo
  end

This calculation will obviously get very big if max is large

Upvotes: 1

Related Questions