Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Math.IEEERemainder() Method in C#
The Math.IEEERemainder() method in C# returns the remainder resulting from the division of a specified number by another specified number. Unlike the modulus operator (%), this method follows the IEEE 754 standard for floating-point arithmetic, which can produce different results in certain cases.
The IEEE remainder is calculated as dividend - (divisor * Math.Round(dividend / divisor)), where the division result is rounded to the nearest even integer when exactly halfway between two integers.
Syntax
public static double IEEERemainder(double dividend, double divisor);
Parameters
- dividend − A double-precision floating-point number (the number to be divided)
- divisor − A double-precision floating-point number (the number to divide by)
Return Value
Returns a double representing the IEEE remainder. If divisor is zero, the method returns NaN (Not a Number). If dividend is infinite, it returns NaN.
Using IEEERemainder with Positive Numbers
Example
using System;
public class Demo {
public static void Main() {
double val1 = 90;
double val2 = 7;
// IEEE Remainder
var ieeeRem = Math.IEEERemainder(val1, val2);
var modRem = val1 % val2;
Console.WriteLine("Dividend: " + val1);
Console.WriteLine("Divisor: " + val2);
Console.WriteLine("IEEE Remainder: " + ieeeRem);
Console.WriteLine("Modulus Result: " + modRem);
}
}
The output of the above code is −
Dividend: 90 Divisor: 7 IEEE Remainder: -1 Modulus Result: 6
Handling Special Cases
Example
using System;
public class Demo {
public static void Main() {
// Division by zero
double val1 = 1;
double val2 = 0;
var rem1 = Math.IEEERemainder(val1, val2);
Console.WriteLine("1 / 0 = " + rem1);
// Infinite dividend
double val3 = Double.PositiveInfinity;
double val4 = 5;
var rem2 = Math.IEEERemainder(val3, val4);
Console.WriteLine("Infinity / 5 = " + rem2);
// Normal case with negative result
double val5 = 10;
double val6 = 3;
var rem3 = Math.IEEERemainder(val5, val6);
Console.WriteLine("10 / 3 = " + rem3);
}
}
The output of the above code is −
1 / 0 = NaN Infinity / 5 = NaN 10 / 3 = 1
Comparison with Modulus Operator
| Operation | IEEERemainder | Modulus (%) |
|---|---|---|
| 90 / 7 | -1 | 6 |
| 10 / 3 | 1 | 1 |
| 5 / 2 | 1 | 1 |
| Division by 0 | NaN | NaN |
Conclusion
The Math.IEEERemainder() method follows the IEEE 754 standard for calculating remainders, which rounds the quotient to the nearest even integer before computing the remainder. This can produce different results compared to the modulus operator, especially when the quotient is close to a half-integer value.
