# 查找具有相同內部表示的float/double的最小值/最大值

Disclaimer: for this discussion, I like to stick to 32 bit and 64 bit floating point as described by IEEE-754. I'm not interested in extended floating point (80-bits) or quads (128 bits IEEE-754-2008) or any other standard (IEEE-854).

Background: Computers are bad at representing 0.1 in binary representation. In C#, a float represents this as 3DCCCCCD internally (C# uses round-to-nearest) and a double as 3FB999999999999A. The same bit patterns are used for decimal 0.100000005 (float) and 0.1000000000000000124 (double), but not for 0.1000000000000000144 (double).

string GetHex(float f)
{
return BitConverter.ToUInt32(BitConverter.GetBytes(f), 0).ToString("X");
}

string GetHex(double d)
{
return BitConverter.ToUInt64(BitConverter.GetBytes(d), 0).ToString("X");
}

// float
Console.WriteLine(GetHex(0.1F));

// double
Console.WriteLine(GetHex(0.1));


0.1 的情況下，不存在用相同位模式表示的小數，任何 0.99 ... 99 將產生不同的位表示（即，對於 0.999999937 的float在內部產生 3F7FFFFF ）。

My question is simple: how can I find the lowest and highest decimal value for a given float (or double) that is internally stored in the same binary representation.

Why: (I know you'll ask) to find the error in rounding in .NET when it converts to a string and when it converts from a string, to find the internal exact value and to understand my own rounding errors better.

## 最佳答案

float absX = absoluteValue(x);
uint32_t bitPattern = getRepresentationOfFloat(absx);
bitPattern++;
float nextFloatNumber = getFloatFromRepresentation(bitPattern);
float ulpOfX = (nextFloatNumber - absX);


This works because adding one to the bit pattern of x exactly corresponds to adding one ulp to the value of x. No floating-point rounding occurs in the subtraction because the values involved are so close (in particular, there is a theorem of ieee-754 floating-point arithmetic that if two numbers x and y satisfy y/2 <= x <= 2y, then x - y is computed exactly). The only caveats here are:

1. 如果x碰巧是最大的有限浮點數，這將不起作用（它會返回 inf ，這顯然是錯誤的）。
2. 如果您的平臺不能正確支持逐漸下溢（例如嵌入式設備以flush-to-zero模式運行），則對於非常小的x值不適用。

One other note the following statement in your question: