[Thread Prev][Thread Next][Index]

Re: [ferret_users] Function MOD : strange behavior



Hi Olivier,

On Wed, Aug 26, 2020 at 5:45 PM Olivier Marti <olivier.marti@xxxxxxxxxxxx> wrote:

yes? LIST MOD(lon    ,360), MOD(lon-360,360), MOD(lon-720,360), MOD(lon+360,360)
[ . . . ]
            EX#1   EX#2   EX#3   EX#4
1    /  1:   36.0 -324.0 -324.0   36.0

[ . . . ] 

The result of EX#2 and EX#3 puzzles me. From what I remember from my math studies, the MOD function should return a result in the interval [0,360[. All EX#s should print the same result than EX#1 and EX#4.

Is this a bug or a feature ? If this is a feature, it should be at last documented. And another MOD function with the "correct" behaviour would be strongly appreciated ;-)

This Q&A session

https://stackoverflow.com/questions/11720656/modulo-operation-with-negative-numbers

explains why Ferret's MOD is the "correct" one.

(m div n) * n + (m mod n) == m
 
shall be an identity for any integers m and n.  Therefore,

(m mod n) = m - (m div n) * n
          = (-324) - ( -324 div 360) * 360
          = -324 - 0 * 360
          = -324

*Your* "correct" mod is found in the form of the MODULO function in Fortran.  I don't know whether Ferret implements it or not.

To visualize what's going on, imaging an axis with integer labels and divide it into segments with a length of 360.

The MODULO(m, 360) function you want measures the distance of m from the nearest left edge of the segment. In contrast, the MOD(m, 360) function finds a vector from the nearest edge closer to 0, to m.  The vector can be leftward (negative) or rightward (positive).

By the way, for the above identity to hold for the MODULO function, we would have to redefine

-324 div 360 = -1

This kind of makes sense.  Because MODULO is one-sided (always measures from the left edge of the interval), DIV should be one-sided, too, to be consistent.

Regards,
Ryo


[Thread Prev][Thread Next][Index]
Contact Us
Dept of Commerce / NOAA / OAR / PMEL / Ferret

Privacy Policy | Disclaimer | Accessibility Statement