Reputation: 39208
In C#, is there an exact equivalent of C99 / IEEE 754's remainder()
function?
The C# language specification says that operator %(double x, double y)
is "analogous to that used for integer operands, but differs from the IEEE 754 definition (in which n
is the integer closest to x / y
)".
For an example of the difference, this C# program outputs two 1's:
using System;
public class Test
{
public static void Main()
{
Console.WriteLine(5.0 % 2.0);
Console.WriteLine(3.0 % 2.0);
}
}
whereas the analogous C program outputs 1 and -1:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%f\n", remainder(5.0, 2.0));
printf("%f\n", remainder(3.0, 2.0));
return EXIT_SUCCESS;
}
Upvotes: 4
Views: 241
Reputation: 34581
This method implements the IEEE 754 remainder algorithm:
Math.IEEERemainder(double, double)
public class Test
{
public static void Main()
{
Console.WriteLine(Math.IEEERemainder(5.0, 2.0));
Console.WriteLine(Math.IEEERemainder(3.0, 2.0));
}
}
// Output: 1, -1
Upvotes: 4