Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does modulus operation works with float data type?

I m trying to find out a simple modulus operation on float data type.

float a=3.14f;
float b=10f;
result=a%b;

I m getting result= 3.14

Another example using decimal data types:

decimal p=10;
decimal q=40;
result=p%q;

getting answer=20.

I am not understanding how does modulus works?

like image 271
user3117347 Avatar asked Dec 19 '13 00:12

user3117347


People also ask

Does modulus operator work on float?

% operator cannot be used with floating point numbers in C & C++.

How do you use the float modulo operator?

The modulus is basically finding the remainder. For this, we can use the remainder() function in C. The remainder() function is used to compute the floating point remainder of numerator/denominator. So the remainder(x, y) will be like below.

Can modulus operator be used with float Java?

As we learn in first paragraph, in Java modulus, operator can also be applied to floating-point numbers e.g. 3.0%1.0 is perfectly legal in Java. Since it return remainder value in division operation it is also known as remainder operator.

Which data type is used for modulus operator?

Datatypes of Operands to Modulus Operator C++ Modulus Operator takes only signed or unsigned integer datatypes.


1 Answers

From the C# language spec on floating point remainder. In the case of x % y if x and y are positive finite values.

z is the result of x % y and is computed as x – n * y, where n is the largest possible integer that is less than or equal to x / y.

The C# language spec also clearly outlines the table of what to do with the cases of all possible combinations of nonzero finite values, zeros, infinities, and NaN’s which can occur with floating point values of x % y.

                          y value

                | +y  –y  +0  –0  +∞  –∞  NaN
           -----+----------------------------  
  x         +x  | +z  +z  NaN NaN x   x   NaN
            –x  | –z  –z  NaN NaN –x  –x  NaN
  v         +0  | +0  +0  NaN NaN +0  +0  NaN
  a         –0  | –0  –0  NaN NaN –0  –0  NaN
  l         +∞  | NaN NaN NaN NaN NaN NaN NaN
  u         –∞  | NaN NaN NaN NaN NaN NaN NaN
  e         NaN | NaN NaN NaN NaN NaN NaN NaN
like image 133
AlexC Avatar answered Sep 24 '22 07:09

AlexC