在.NET中查找一个浮点数是另一个浮点数的倍数

编程入门 行业动态 更新时间:2024-10-28 17:15:40
本文介绍了在.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​​(余数)<公差) { / /余数几乎是除数的倍数,所以我们会说这是一个多元

你可以决定一个足够小的容忍值。有时使用机器eps 进行这种检查,但可能太低。如果 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中查找一个浮点数是另一个浮点数的倍数

本文发布于:2023-08-07 19:57:45,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点数   倍数   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!