use*_*466 0 floating-point precision numbers range
有多少个不同的数字是从1.5 x 10 -45到3.4 x 10 38(IEE754单精度浮点数)?
And*_*w Y 23
假设您正在讨论IEEE单精度浮点数的范围(1.5 x 10 ^ -45是最小正值,它可以表示它可以表示,3.4 x 10 ^ 38是最大正值)
我们将为这个数字占用的4个字节设置以下可能的布局:
0 00000000 00000000000000000000000 = 0
0 00000000 00000000000000000000001 = 1.5 x 10^-45
......
0 11111110 11111111111111111111111 = 3.4 x 10^38
0 11111111 00000000000000000000000 = Infinity
0 11111111 xxxxxxxxxxxxxxxxxxxxxxx = NaNs
Run Code Online (Sandbox Code Playgroud)
哪个应该在两者之间给我们2139095037个数字.
当然,对于任何两个浮点数一般来说,这可以通过programmaticaly进行."词典索引"是浮点数的有序索引,可用于其他因素,因为IEEE 754的设计方式使其易于生成.
对于任何两个花车,基本规则是,如果(float1 > float2)那么(lexIndex1 > lexIndex2).
因此,计算IEEE 754之间的数字是减去两个数字的词典索引的问题:
public class FloatUtil
{
public static uint ToLexicographicIndex(float value)
{
//transfer bits to an int variable
int signed32 = BitConverter.ToInt32(BitConverter.GetBytes(value), 0);
uint unsigned32 = (uint)signed32;
//(0x80000000 - unsigned32) returns
//appropriate index for negative numbers
return (signed32 >= 0)
? unsigned32
: 0x80000000 - unsigned32;
}
public static uint NumbersBetween(float value1, float value2)
{
if (float.IsNaN(value1) || float.IsInfinity(value1))
{
throw new ArgumentException("value1");
}
if (float.IsNaN(value2) || float.IsInfinity(value2))
{
throw new ArgumentException("value2");
}
uint li1 = ToLexicographicIndex(value1);
uint li2 = ToLexicographicIndex(value2);
//make sure return is positive
return value1 >= value2 ? li1 - li2 : li2 - li1;
}
}
Run Code Online (Sandbox Code Playgroud)
当然,在这种情况下的用法:
uint result = FloatUtil.NumbersBetween(1.5e-45f, 3.4e+38f);
Run Code Online (Sandbox Code Playgroud)
在这种情况下,结果是2139081117C#中的这些数字,因为3.4e+38f常量表达式不会编译到float范围的最大值.但是,使用float.MaxValue(3.40282347E+38)作为第二个数字给出了预期的数字,2139095038.
| 归档时间: |
|
| 查看次数: |
2772 次 |
| 最近记录: |