Floating point comparison functions for C#(C# 的浮点比较函数)
问题描述
有人可以指出(或展示)C# 中一些很好的通用浮点比较函数来比较浮点值吗?我想为 IsEqual
、IsGreater
和 IsLess
实现函数.我也只关心双打而不是花车.
Can someone point towards (or show) some good general floating point comparison functions in C# for comparing floating point values? I want to implement functions for IsEqual
, IsGreater
an IsLess
. I also only really care about doubles not floats.
推荐答案
编写一个有用的通用浮点 IsEqual
非常非常困难,如果不是完全不可能的话.对于 a==0
,您当前的代码将严重失败.该方法在这种情况下的行为方式实际上是一个定义问题,并且可以说代码最好针对特定的域用例进行定制.
Writing a useful general-purpose floating point IsEqual
is very, very hard, if not outright impossible. Your current code will fail badly for a==0
. How the method should behave for such cases is really a matter of definition, and arguably the code would best be tailored for the specific domain use case.
对于这种事情,你真的,真的需要一个好的测试套件.这就是我为浮点指南所做的,这就是我想出的最后加上(Java 代码,应该很容易翻译):
For this kind of thing, you really, really need a good test suite. That's how I did it for The Floating-Point Guide, this is what I came up with in the end (Java code, should be easy enough to translate):
您还可以在网站上找到测试套件.
You can also find the test suite on the site.
附录:在 c# 中用于双打的相同代码(如问题中所问)
Appendix: Same code in c# for doubles (as asked in questions)
这篇关于C# 的浮点比较函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!