Daniel Trebbien
Daniel Trebbien

Reputation: 39208

C# equivalent of IEEE 754 remainder()?

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);
    }
}

http://ideone.com/GBITYq

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;
}

http://ideone.com/HpuIVr

Upvotes: 4

Views: 241

Answers (1)

Dmytro Shevchenko
Dmytro Shevchenko

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

http://ideone.com/b2Lvfx

Upvotes: 4

Related Questions