Search code examples
cmatlabfmodmodulo

How does fmod() in c work compared with matlab mod()?


In matlab code

    Longitude =  mod(-1789.8916,360);

returns value 10.108325

But in C code

    Longitude = fmod(-1789.8916,360);

returns value -349.8916

I want the value same as in the c code


Solution

  • The matlab mod function always returns a positive value, but the C fmod function (from C11 at least) will return a negative value if the first argument is negative. (In prior C standards the precise behaviour for a negative argument was up to the implementation).

    So you can transform the matlab version by subtracting 360 (in this case) from the answer if the first argument is negative and the result greater than zero.