本文介绍了在.NET中查找一个浮点数是另一个浮点数的倍数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何找到一个浮点数是否是另一个浮点数的倍数?

500.4是0.001的倍数?

  double v = 500.4; 
double multipleOf = 0.001;

double remainder = v%multipleOf;
// 0.000999999999966846

对于性能,我不希望将双精度转换为小数。如果给定浮点数学的不精确性,我该如何测试呢?

您可以确定如果余数与您的 multipleOf {
//

  (Math.Abs​​(multipleOf) -  Math.Abs​​(余数)<公差)
{
/ /余数几乎是除数的倍数,所以我们会说这是一个多元

你可以决定一个足够小的容忍值。有时使用进行这种检查,但可能太低。如果 v 非常大, multipleOf 非常小,我们可以说这个问题是有缺陷的,因为容忍可能需要如此高的结果对于您的应用程序所要求的准确度级别来说将毫无用处。因此,搜索调节和精度也可能会引起更多关注。


How can I find if one floating point number is a multiple of another?

e.g. Is 500.4 a multiple of 0.001?

double v = 500.4;
double multipleOf = 0.001;

double remainder = v % multipleOf;
// 0.000999999999966846

For performance I'd prefer not converting the doubles to decimals. How can I test this given the imprecise nature of floating point math?

解决方案

You would determine if the remainder is below an acceptable tolerance to your problem or if the remainder is very close to your 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
}

Only you can decide on a small enough value for tolerance. Sometimes machine epsilon is used for this type of check but it might be too low. If v is very large and multipleOf very small we might say the problem is ill conditioned because the tolerance might need to be so high the results would be useless for the level of accuracy you require in your application. So searching for Conditioning and Precision might be of further interest as well.

这篇关于在.NET中查找一个浮点数是另一个浮点数的倍数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-15 20:41