Why do both % and fmod() exist in C - c

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?

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.

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

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

% is just integer modulo
fmod is float modulo and can be used as described in MSDN.
https://msdn.microsoft.com/en-us/library/20dckbeh.aspx

Related

Does data types change the output of an operation in C [duplicate]

This question already has answers here:
What is the behavior of integer division?
(6 answers)
Closed last year.
Iam new to C programming and i guess this question might look foolish but I have searched and i didn't get a satisfactory answer:
My question is does hierachy of execution of operators depend on whether the declared variables are integer or float, here is a scenario which I don't understand;
this is the first case:
main()
{
int i=2,j=3,k;
k=i/j*j;
printf("%d",k);
and the output to that is 0 which i don't agree with;
But when I change the variables to float as in below;
main()
{
float i=2,j=3,k;
k=i/j*j;
printf("%f",k);
The output to becomes 2.00000
why is this?
In the first code snippet, the subexpression i/j has integer operands so integer division is performed. This means that the result is also an integer and any fractional part is truncated.
In the second snippet, both operands have floating point type so floating point division is performed.
and the output to that is 0 which i don't agree with;
The program is always right, people (programmers) do mistakes.
The operation below is an integer division and 2 divided by 3 is 0. Integer division does not round to the closest integer value which causes your confusuin.
i/j == 2/3 == 0
does hierachy of execution of operators depend on whether the declared variables are integer or float?
Hierarchy of execution as in order, no.
However, results very much depend on the types. Division involving two integers results in a truncated integer, so 2 / 3 is zero, not two thirds as you may expect.
Then, when you multiply that by two, you still have zero.
An example can be seen when calculating percentage of a ratio. Let's say 40 of the 60 students in a class are male. If you wanted to know the percentage of males, there's a vast difference between the two formulae below:
int males = 40;
int total = 60;
bad_pct = males / total * 100; // 40/60=0, 0*100=0.
good_pct = males * 100 / total; // 40*100=4000, 4000/60=66.
The issue of integer math vs. floating point math has been dealt with well already, but when you use the term "hierarchy of operators," I think you're referring to operator precedence.
No, it does not change this. Operator precedence is the same for floating point and integer math operations.

Modulo Operator don't work in my calculator app in C [duplicate]

I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
Given a periodic function (e.g. sin) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
The "obvious" solution is something like:
#include <cmath>
float sin(float x){
return limited_sin((x + M_PI) % (2 *M_PI) - M_PI);
}
Why doesn't this work? I get this error:
error: invalid operands of types double and double to binary operator %
Interestingly, it does work in Python:
def sin(x):
return limited_sin((x + math.pi) % (2 * math.pi) - math.pi)
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod function, as well as remainder function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
You're looking for fmod().
I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.
EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.
I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.
The modulo operator % in C and C++ is defined for two integers, however, there is an fmod() function available for usage with doubles.
The constraints are in the standards:
C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators
Each of the operands shall have arithmetic type. The operands of the % operator shall
have integer type.
C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration
type. The usual arithmetic conversions are performed on the operands and determine the type of the result.
The solution is to use fmod, which is exactly why the operands of % are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators:
The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod
try fmod
"The mathematical notion of modulo arithmetic works for floating point
values as well, and this is one of the first issues that Donald Knuth
discusses in his classic The Art of Computer Programming (volume I).
I.e. it was once basic knowledge."
The floating point modulus operator is defined as follows:
m = num - iquot*den ; where iquot = int( num/den )
As indicated, the no-op of the % operator on floating point numbers appears
to be standards related. The CRTL provides 'fmod', and usually 'remainder'
as well, to perform % on fp numbers. The difference between these two lies
in how they handle the intermediate 'iquot' rounding.
'remainder' uses round-to-nearest, and 'fmod' uses simple truncate.
If you write your own C++ numerical classes, nothing prevents you
from amending the no-op legacy, by including an overloaded operator %.
Best Regards
The % operator does not work in C++, when you are trying to find the remainder of two numbers which are both of the type Float or Double.
Hence you could try using the fmod function from math.h / cmath.h or you could use these lines of code to avoid using that header file:
float sin(float x) {
float temp;
temp = (x + M_PI) / ((2 *M_PI) - M_PI);
return limited_sin((x + M_PI) - ((2 *M_PI) - M_PI) * temp));
}
For C/C++, this is only defined for integer operations.
Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:
>>> 4 % math.pi
0.85840734641020688
>>> 4 - math.pi
0.85840734641020688
>>>

Eigen::Matrix modulus fails to compile [duplicate]

I recently ran into an issue that could easily be solved using modulus division, but the input was a float:
Given a periodic function (e.g. sin) and a computer function that can only compute it within the period range (e.g. [-π, π]), make a function that can handle any input.
The "obvious" solution is something like:
#include <cmath>
float sin(float x){
return limited_sin((x + M_PI) % (2 *M_PI) - M_PI);
}
Why doesn't this work? I get this error:
error: invalid operands of types double and double to binary operator %
Interestingly, it does work in Python:
def sin(x):
return limited_sin((x + math.pi) % (2 * math.pi) - math.pi)
Because the normal mathematical notion of "remainder" is only applicable to integer division. i.e. division that is required to generate integer quotient.
In order to extend the concept of "remainder" to real numbers you have to introduce a new kind of "hybrid" operation that would generate integer quotient for real operands. Core C language does not support such operation, but it is provided as a standard library fmod function, as well as remainder function in C99. (Note that these functions are not the same and have some peculiarities. In particular, they do not follow the rounding rules of integer division.)
You're looking for fmod().
I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.
EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.
I can't really say for sure, but I'd guess it's mostly historical. Quite a few early C compilers didn't support floating point at all. It was added on later, and even then not as completely -- mostly the data type was added, and the most primitive operations supported in the language, but everything else left to the standard library.
The modulo operator % in C and C++ is defined for two integers, however, there is an fmod() function available for usage with doubles.
The constraints are in the standards:
C11(ISO/IEC 9899:201x) §6.5.5 Multiplicative operators
Each of the operands shall have arithmetic type. The operands of the % operator shall
have integer type.
C++11(ISO/IEC 14882:2011) §5.6 Multiplicative operators
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration
type. The usual arithmetic conversions are performed on the operands and determine the type of the result.
The solution is to use fmod, which is exactly why the operands of % are limited to integer type in the first place, according to C99 Rationale §6.5.5 Multiplicative operators:
The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod
try fmod
"The mathematical notion of modulo arithmetic works for floating point
values as well, and this is one of the first issues that Donald Knuth
discusses in his classic The Art of Computer Programming (volume I).
I.e. it was once basic knowledge."
The floating point modulus operator is defined as follows:
m = num - iquot*den ; where iquot = int( num/den )
As indicated, the no-op of the % operator on floating point numbers appears
to be standards related. The CRTL provides 'fmod', and usually 'remainder'
as well, to perform % on fp numbers. The difference between these two lies
in how they handle the intermediate 'iquot' rounding.
'remainder' uses round-to-nearest, and 'fmod' uses simple truncate.
If you write your own C++ numerical classes, nothing prevents you
from amending the no-op legacy, by including an overloaded operator %.
Best Regards
The % operator does not work in C++, when you are trying to find the remainder of two numbers which are both of the type Float or Double.
Hence you could try using the fmod function from math.h / cmath.h or you could use these lines of code to avoid using that header file:
float sin(float x) {
float temp;
temp = (x + M_PI) / ((2 *M_PI) - M_PI);
return limited_sin((x + M_PI) - ((2 *M_PI) - M_PI) * temp));
}
For C/C++, this is only defined for integer operations.
Python is a little broader and allows you to get the remainder of a floating point number for the remainder of how many times number can be divided into it:
>>> 4 % math.pi
0.85840734641020688
>>> 4 - math.pi
0.85840734641020688
>>>

jeo=(1/(1+decade)); not giving me accurate answer

int decade;
float jeo;
PRINT("Enter Decade point =\r\n");
scanf("%d",&decade);
print_decimal(decade);
PRINT("\r\n");
jeo=(1/(1+decade));
PRINT("Decade point =");
print_decimal(jeo);//my function for showing floating point number.
PRINT("\r\n");
I have wrote this code in IAR embedded workbench software for ARM controller, but it's not giving me accurate answer, can anyone tell me why??
"when i am entering 3. it's giving me 0 answer".
You are just doing your calculation with integer and assign afterwards to a float value. This will remove the digits after the decimal point.
Try this:
jeo=(1.0/(1.0+decade));
You are assigning the result of an integer division to jeo. In this case, if decade is any integer other than 0, the result of integer division will be 0. (Note: If decade is -1, you will have undefined behavior as a result of division by 0)
When the type after usual arithmetic conversions is an integer type, the result is the algebraic quotient (not a fraction), rounded in implementation-defined direction (until C99)truncated towards zero (since C99)
So make either the numerator or the denominator a float.
jeo=((float)1/float(1+decade);
Try this
jeo=1/(1+float(decade));
this is because when trying to employ an integer in a logical expression like that, the result is calculated in integer first then converted to float. This procedure ,of course, removes the digits after the decimal point and adds artificial 0s.

Why does division result in zero instead of a decimal?

Teaching myself C and finding that when I do an equation for a temp conversion it won't work unless I change the fraction to a decimal. ie,
tempC=(.555*(tempF-32)) will work but tempC=((5/9)*(tempF-32)) won't work.
Why?
According to the book "C Primer Plus" it should work as I'm using floats for both tempC and tempF.
It looks like you have integer division in the second case:
tempC=((5/9)*(tempF-32))
The 5 / 9 will get truncated to zero.
To fix that, you need to make one of them a floating-point type:
tempC=((5./9.)*(tempF-32))
When you do 5/9, 5 and 9 are both integers and integer division happens. The result of integer division is an integer and it is the quotient of the two operands. So, the quotient in case of 5/9 is 0 and since you multiply by 0, tempC comes out to be 0. In order to not have integer division, atleast one of the two operands must be float.
E.g. if you use 5.0/9 or 5/9.0 or 5.0/9.0, it will work as expected.
5/9 is an integer division not a floating point division. That's why you are getting wrong result.
Make 5 or 9 floating point variable and you will get correct answer.
Like 5.0/9 OR 5/9.0
5/9 is an integer expression, as such it gets truncated to 0. your compiler should warn you about this, else you should look into enabling warnings.
If you put 5/9 in parenthesis, this will be calculated first, and since those are two integers, it will be done by integer division and the result will be 0, before the rest of the expression is evaluated.
You can rearrange your expression so that the conversion to float occurs first:
tempC=((5/9)*(tempF-32)); → tempC=(5*(tempF-32))/9;
or of course, as the others say, use floating point constants.

Resources