我正在为一位同事写一个有启发性的例子,告诉他为什么测试花车的平等往往是个坏主意.我去的例子是添加0.1十次,对1.0(我在我的介绍数值类所示)进行比较.我惊讶地发现两个结果是相同的(代码+输出).
float @float = 0.0f;
for(int @int = 0; @int < 10; @int += 1)
{
@float += 0.1f;
}
Console.WriteLine(@float == 1.0f);
Run Code Online (Sandbox Code Playgroud)
一些调查表明,这个结果不能依赖(很像浮动平等).我发现最令人惊讶的是在其他代码之后添加代码可能会改变计算结果(代码+输出).请注意,此示例具有完全相同的代码和IL,并附加了一行C#.
float @float = 0.0f;
for(int @int = 0; @int < 10; @int += 1)
{
@float += 0.1f;
}
Console.WriteLine(@float == 1.0f);
Console.WriteLine(@float.ToString("G9"));
Run Code Online (Sandbox Code Playgroud)
我知道我不应该在花车上使用平等,因此不应该太在意这一点,但我发现它非常令人惊讶,就像我向大家证明的那样.做的东西后,您进行了计算改变了先前计算的价值?我不认为这是人们通常在脑海中计算的模型.
我不是完全难住了,似乎是安全的假设,有某种优化的改变计算的结果,"平等"的情况下发生的(建筑在调试模式防止"平等"的情况下).显然,当CLR发现稍后需要将浮动框打包时,优化被放弃.
我搜索了一下但找不到这种行为的原因.任何人都能提醒我吗?
我已经建立了一个网站,它接受代码片段并编译它们并运行它们.但是,F#在服务器上被破坏了.每当我尝试编译F#代码时,我都会收到以下错误消息:
The referenced or default base CLI library 'mscorlib' is binary-incompatible with the referenced F# core library 'C:\Program Files (x86)\Microsoft F#\v4.0\FSharp.Core.dll'. Consider recompiling the library or making an explicit reference to a version of this library that matches the CLI version you are using.
Error opening binary file 'C:\Program Files (x86)\Microsoft F#\v4.0\FSharp.Core.dll': Exception of type 'Microsoft.FSharp.Compiler.ErrorLogger+ReportedError' was thrown.
To be clear, this is an error being returned by the compiler, not an error that occurs when the code is run. …