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".
Asked
Active
Viewed 110 times
0
-
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 Answers
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
-
Sometimes there is no next value, and you should deal with negative values, but I like this idea – Sergey Berezovskiy Feb 21 '14 at 11:48
-
Yes, there are several cases not handled. But this is a general idea. – Alex Watson Feb 21 '14 at 11:49