user3117347
user3117347

Reputation: 163

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?

Upvotes: 13

Views: 33993

Answers (3)

taco_parcel
taco_parcel

Reputation: 13

This question is old, but I had to recreate its issues recent in python, so I figured I'd add an answer here. C# demonstration of the problem:

var incorrect = (1286212381 % 1000.0f);
Console.WriteLine(incorrect);

var incorrect2 = (1286212381.0f % 1000.0f);
Console.WriteLine(incorrect2);

var correct = Math.IEEERemainder(1286212381, 1000.0f);
Console.WriteLine(correct);

Console.WriteLine("Correct answer is 381, incorrect is 352.");

To get an implementation that matches in python, required using a float32 from numpy because you need the floating point imprecision.

import numpy as np

def float_remainder_matching_csharp(v1, v2):
    denominator = np.float32(v1)
    modifier = np.float32(v2)
    rem = denominator % modifier
    real_ret_val = rem.item()
    return real_ret_val

mod = float_remainder_matching_csharp(1286212381, 1000.0)
print(mod)

Upvotes: 1

AlexC
AlexC

Reputation: 10756

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

Upvotes: 21

evanmcdonnal
evanmcdonnal

Reputation: 48076

This article on msdn has sufficient example but I can explain it real quick;

http://msdn.microsoft.com/en-us/library/0w4e0fzs.aspx

If you do int result = x % y; what you'll find is that you are returned the remainder of x % y and the values are treated more like whole numbers. For example, the third line in the link is Console.WriteLine(5.0 % 2.2); which prints .6. This is because it finds that 2.2 can go into 5.0 no more than twice. So it does 5 - 2.2(2) which is .6

Upvotes: 7

Related Questions