【问题标题】:Finding if one floating point number is a multiple of another in .NET在.NET中查找一个浮点数是否是另一个浮点数的倍数
【发布时间】:2016-06-09 03:41:31
【问题描述】:

如何判断一个浮点数是否是另一个浮点数的倍数?

例如500.4 是 0.001 的倍数吗?

double v = 500.4;
double multipleOf = 0.001;

double remainder = v % multipleOf;
// 0.000999999999966846

出于性能考虑,我不希望将双精度数转换为小数。考虑到浮点数学的不精确性,我该如何测试?

【问题讨论】:

  • 我想这取决于你对多重的定义
  • 这不是一个有意义的问题。将所有内容乘以 1000,这样您就可以使用像 intlong 这样的整数类型。或者使用 epsilon 来称呼它“足够接近”。
  • 如果您要乘以将值转换为整数,如何找出双精度数中有多少个小数? multipleOf * Math.Pow(10, ?)
  • 我已经更新了我的答案,因为它缺少检查(它不处理负值,但我认为您可以轻松地自己添加)。这是我所知道的关于浮点比较的最有用的文章,它可以让您进一步了解这个问题:Comparing Floating Point Numbers, 2012 Edition

标签: .net floating-point


【解决方案1】:

您将确定remainder 是否低于您的问题可接受的容差,或者remainder 是否非常接近您的multipleOf

if (Math.Abs(remainder) < tolerance)
{
   //remainder is negligible so we'll say it's a multiple
}
else if (Math.Abs(multipleOf) - Math.Abs(remainder) < tolerance)
{
   //remainder is almost multiple of divisor so we'll say it's a multiple
}

只有您可以决定一个足够小的公差值。有时machine epsilon 用于这种类型的检查,但它可能太低了。如果v 非常大而multipleOf 非常小,我们可能会说问题是病态的,因为公差可能需要非常高,结果对于您在应用程序中所需的精度水平将毫无用处。因此,搜索 Conditioning and Precision 可能还有更多的兴趣。

【讨论】:

    猜你喜欢
    • 2012-09-07
    • 1970-01-01
    • 2014-02-18
    • 2014-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-07
    • 1970-01-01
    相关资源
    最近更新 更多