比较两个浮筒 [英] Compare two floats

查看:112
本文介绍了比较两个浮筒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdbool.h>

bool Equality(double a, double b, double epsilon)
{
  if (fabs(a-b) < epsilon) return true;
  return false;
}

我试过这个方法来比较两个双打,但我总是问题,因为我不知道该如何选择了小量,其实我想小的数字比较(小数点后6 6位)喜欢的 0.000001 的。我试着用一些数字,有时我得到 0.000001!= 0.000001 有时 0.000001 0.000002 = =
难道还有比用小量其他比较其他方法?

I tried this method to compare two doubles, but I always get problems since I don't know how to chose the epsilon, actually I want to compare small numbers (6 6 digits after the decimal point) like 0.000001. I tried with some numbers, sometimes I get 0.000001 != 0.000001 and sometimes 0.000001 == 0.000002 Is there another method else than comparing with the epsilon?

我的目的是比较两个双打(其中重present在我的案件的时间)。这将重新$ P $变量t psents以毫秒为单位是双。它是由另一个函数0.000001 0.000002再等等,每次T改变递增,我要检查它是否等于double类型TT的另一个变量,万一TT == T,我有一些指令来执行..结果
感谢您的帮助。

My purpose is to compare two doubles (which represent the time in my case). The variable t which represents the time in milliseconds is a double. It is incremented by another function 0.000001 then 0.000002 etc. each time t changes, I want to check if it is equal to another variable of type double tt, in case tt == t, I have some instructions to execute..
Thanks for your help

推荐答案

看看这里: HTTP: //floating-point-gui.de/errors/comparison/

由于舍入误差,最浮点数最终被
  稍微IM precise。只要这个IM precision留小,它可以
  通常被忽略。的然而,这也意味着,数字预期为
  相等(例如计算通过不同的正确相同的结果时,
  方法)经常略有不同,和一个简单的平等的测试失败

Due to rounding errors, most floating-point numbers end up being slightly imprecise. As long as this imprecision stays small, it can usually be ignored. However, it also means that numbers expected to be equal (e.g. when calculating the same result through different correct methods) often differ slightly, and a simple equality test fails.

和,当然,什么每个计算机科学家应该知道关于浮点运算

这篇关于比较两个浮筒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆