如何确定两个变量是否近似相等?

编程入门 行业动态 更新时间:2024-10-27 18:25:50
本文介绍了如何确定两个变量是否近似相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写单元测试来验证数据库中的计算,并且有很多四舍五入和截断等内容,这意味着有时数字会略有偏差.

I am writing unit tests that verify calculations in a database and there is a lot of rounding and truncating and stuff that mean that sometimes figures are slightly off.

在验证时,我发现很多时候事情会通过但会说失败 - 例如,数字是 1 而我得到的是 0.999999

When verifying, I'm finding a lot of times when things will pass but say they fail - for instance, the figure will be 1 and I'm getting 0.999999

我的意思是,我可以将所有内容四舍五入为一个整数,但由于我使用了大量随机样本,因此最终我会得到这样的结果

I mean, I could just round everything into an integer but since I'm using a lot of randomized samples, eventually i'm going to get something like this

10.510.4999999999

10.5 10.4999999999

一个将四舍五入到 10,另一个将四舍五入到 11.

one is going to round to 10, the other will round to 11.

如果我需要一些大致正确的东西,我应该如何解决这个问题?

How should I solve this problem where I need something to be approximately correct?

推荐答案

定义一个容差值(又名 'epsilon' 或 'delta'),例如 0.00001,然后像这样用来比较差异:

Define a tolerance value (aka an 'epsilon' or 'delta'), for instance, 0.00001, and then use to compare the difference like so:

if (Math.Abs(a - b) < delta) { // Values are within specified tolerance of each other.... }

您可以使用 Double.Epsilon,但您必须使用乘数.

You could use Double.Epsilon but you would have to use a multiplying factor.

更好的是,编写一个扩展方法来做同样的事情.我们的单元测试中有类似 Assert.AreSimilial(a,b) 的东西.

Better still, write an extension method to do the same. We have something like Assert.AreSimiliar(a,b) in our unit tests.

Microsoft 的 Assert.AreEqual() 方法有一个带增量的重载:public static void AreEqual(double expected, double actual, double delta)

Microsoft's Assert.AreEqual() method has an overload that takes a delta: public static void AreEqual(double expected, double actual, double delta)

NUnit 还为其 Assert.AreEqual() 方法提供了一个重载,允许提供一个增量.

NUnit also provides an overload to their Assert.AreEqual() method that allows for a delta to be provided.

更多推荐

如何确定两个变量是否近似相等?

本文发布于:2023-11-08 13:21:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569480.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:近似   变量   两个

发布评论

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

>www.elefans.com

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