0

Is there a way to retrieve the successor or the predecessor a certain double? Note that I'm not looking for a "small constant", like double.Epsilon, but for "the smallest positive number that can be added or subtracted from a given value".

Starnuto di topo
  • 3,215
  • 5
  • 32
  • 66
  • I think C# uses the regular (standardized) floating point operations, so from its bit form you can generate the successor and predecessor values for most of the values. – Gábor Bakos Feb 21 '14 at 11:40

1 Answers1

1

You could take binary representation and add one to the fraction part. Example:

using System;

public class Test
{
    static void DoubleTest(double value)
    {
        var binary = BitConverter.DoubleToInt64Bits(value);
        binary++;
        var newValue = BitConverter.Int64BitsToDouble(binary);
        var difference = newValue - value;
        Console.WriteLine("value  = {0:R}", value);
        Console.WriteLine("value' = {0:R}", newValue);
        Console.WriteLine("dx     = {0:R}", difference);
        Console.WriteLine();
    }
    public static void Main()
    {
        DoubleTest(0.0000000004);
        DoubleTest(4.0000000000);
        DoubleTest(4000000000.0);
    }
}

prints:

value  = 4E-10
value' = 4.0000000000000007E-10
dx     = 5.169878828456423E-26

value  = 4
value' = 4.0000000000000009
dx     = 8.8817841970012523E-16

value  = 4000000000
value' = 4000000000.0000005
dx     = 4.76837158203125E-07
Alex Watson
  • 519
  • 3
  • 13