Silverfrost Forums

Welcome to our forums

concerning the MOD intrinsic function

4 May 2017 6:06 #19575

Dear Silverfrost community: I do not know how to use the MOD intrinsic function. Could you suggest ways that I can learn how to use this function? Thank you.

                                            Best regards,
                                            Carl Mesaros :)
8 May 2017 6:00 #19591

Try something like the following. This may show some of how it works.

integer i,j
do i = -10,10
  j = mod(i,4)
  write (*,*) i,j, mod(i,-4)
end do
end

Note: mod(I+p,p) = mod(I,p) mod (-I,p) = - mod(I,p) mod(I,-p) = mod(I,p) { which can be annoying when 0 < I < p, as mod(I+p,p) = mod(I,p) but mod(I-p,p) /= mod(I,p) }

8 May 2017 11:35 #19598

Quoted from JohnCampbell

mod(I+p,p) = mod(I,p)

Not always!

Counterexample: mod(-2, 3) = -2, but mod(-2+3, 3) = 1

It is quite easy to make such slips if one or both the arguments to the mod() function, or its sister function modulo(), are negative. Modular arithmetic can be counter-intuitive if one is not used to it. For example, (a + b) mod c need not equal (a mod c) + (b mod c); consider a=1, b=1, c=2.

The rule is: Given two numbers (real or integer) A and P, of the same type and kind, find the integer K = INT(A/P) in the case of mod() and K = FLOOR(A/P) in the case of modulo(). The value of the function is A - K*P, and '/' has its mathematical meaning, not 'integer division'.

The functions can be used in a number of situations where one has to find the nearest from a set of discrete values. I use the mod() function frequently in an iterative algorithm to monitor the progress: IF (mod(ITER, PRNTINTVL) == 0) WRITE(,)...

8 May 2017 11:33 #19610

For reporting progress I try to use an alternative form to 'IF (mod(ITER, PRNTINTVL) == 0) WRITE(,)...'

IF ( ITER >= Next_PRNT_ITER ) THEN WRITE(,)... Next_PRNT_ITER = Next_PRNT_ITER + PRNTINTVL END IF

This can create greater flexibility by varying PRNTINTVL or starting with a different Next_PRNT_ITER. The following all give a different initial report, which can be useful for confirming the initial cycling: Next_PRNT_ITER = -PRNTINTVL Next_PRNT_ITER = 0 Next_PRNT_ITER = PRNTINTVL

Please login to reply.