Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do both % and fmod() exist in C

Tags:

c

math.h

I took a quiz in my CS class today and got a question about the modulo operator wrong because I didn't know about the availability of % in C, I've been using fmod(). Why do both exist? Is one better/faster or do they just deal with different data types?

like image 375
John Harlan Avatar asked Jan 25 '17 17:01

John Harlan


3 Answers

modulo division using % operator in C only works for integer operands and returns an integer remainder of the division. The function fmod accepts double as arguments meaning that it accepts non-integer values and returns the remainder of the division.

Additional note on fmod: how is the remainder calculated in case of double operand? Thanks @chux for showing the documentation on how fmod calculates the remainder of a floating point division.

The floating-point remainder of the division operation x/y calculated by this function is exactly the value x - n*y, where n is x/y with its fractional part truncated.

The returned value has the same sign as x and is less or equal to y in magnitude.

On the other hand, when the modulo division binary operator (%) was first designed, it was determined by the language designers that it would only support operands of 'integer' types because technically speaking, the notion of 'remainder' in mathematics only applies to integer divisions.

like image 135
VHS Avatar answered Oct 24 '22 23:10

VHS


It's because % is an integer operator, and fmod stands for floatmod and is used for floating point numbers.

like image 5
xenteros Avatar answered Oct 25 '22 01:10

xenteros


Why do both exist?

Because they may have computed different results, even with the same values. These differences may occur with negative values. In essence fmod() and % were different mathematical functions.

fmod(x,y), since C89, had the result "the result has the same sign as x and magnitude less than the magnitude of y".

i%j was not so singularly defined. See Remainder calculation for the modulo operation. This allow code to use existing variant processors effectively. The div() function was created to address this variability. Ref

By C99 they compute the same for the same values. Future C could allow 123.4 % 56.7

like image 3
chux - Reinstate Monica Avatar answered Oct 25 '22 01:10

chux - Reinstate Monica