浮点运算是太可靠 [英] Floating point arithmetic is too reliable
问题描述
据我了解,在现代计算机系统进行浮点运算并不总是与实数运算是一致的。我想图谋小C#程序来证明这一点。例如:
静态无效的主要(字串[] args)
{
双X = 0,Y = 0;
X + = 20013.8;
X + = 20012.7;
Y + = 10016.4;
Y + = 30010.1;
Console.WriteLine(结果:+ X ++ Y ++(X == Y));
Console.Write(按任意键继续。); Console.ReadKey(真);
}
然而,在这种情况下, X
和是
到底是相等的。
是否有可能对我来说,证明浮动使用类似的复杂程序浮点运算的不一致,并没有使用任何真正疯狂的数字?我想,如果可能的话,避免去比超出小数点少数地方更数学上正确的值。
双X =(0.1 * 3)/ 3;
Console.WriteLine(X:{0},X); //输出X:0.1
Console.WriteLine(X == 0.1:{0}中,x == 0.1); //输出×== 0.1:假
备注:在此基础上不作假设浮点运算是在.NET中不可靠的。
I understand that floating point arithmetic as performed in modern computer systems is not always consistent with real arithmetic. I am trying to contrive a small C# program to demonstrate this. eg:
static void Main(string[] args)
{
double x = 0, y = 0;
x += 20013.8;
x += 20012.7;
y += 10016.4;
y += 30010.1;
Console.WriteLine("Result: "+ x + " " + y + " " + (x==y));
Console.Write("Press any key to continue . . . "); Console.ReadKey(true);
}
However, in this case, x
and y
are equal in the end.
Is it possible for me to demonstrate the inconsistency of floating point arithmetic using a program of similar complexity, and without using any really crazy numbers? I would like, if possible, to avoid mathematically correct values that go more than a few places beyond the decimal point.
double x = (0.1 * 3) / 3;
Console.WriteLine("x: {0}", x); // prints "x: 0.1"
Console.WriteLine("x == 0.1: {0}", x == 0.1); // prints "x == 0.1: False"
Remark: based on this don't make the assumption that floating point arithmetic is unreliable in .NET.
这篇关于浮点运算是太可靠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!