使用==运算符比较两个舍入浮点数是正确的吗? [英] Is it correct to compare two rounded floating point numbers using the == operator?

查看:160
本文介绍了使用==运算符比较两个舍入浮点数是正确的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还是有机会操作失败?

感谢。

我的意思是四舍五入到0,而不是截断。

I chose the wrong term and what I really meant was rounding to 0, not truncation.

关键是,我需要比较两个双精度的整数部分, to int然后使用==,但是,正如我在前面的一个问题中指出,如果double不能适应整数,这可能会引发一个溢出异常。

The point is, I need to compare the integer part of two doubles and I'm just casting them to int and then using ==, but, as someone pointed out in one of my earlier questions, this could throw an overflow exception if the double can't fit into the integer.

所以问题是使用==运算符来比较以前舍入为0的两个双精度,或者我应该坚持转换为int方法并捕获可能的异常吗?

So the question would be 'Is it correct to use the == operator to compare two doubles that have previously been rounded to 0, or should I stick to the casting to int method and catch a possible exception?

推荐答案

这里是更新的网站,其中讨论了几种比较浮点数的方法的优缺点。 (您仍然可以在此查看旧网站。)

Here's the updated site which discusses the pros and cons of several methods of comparing floating point numbers. (You can still view the old site here.)

我想使用的方法是相对错误方法。找到两个数字之间的差异,将其转换为数字的百分比,如果该百分比足够小,那么你就是平等的。

The method I'd go with is the "relative error" method. Find the difference between the two numbers, convert that to a percentage of the numbers, and if that percentage is sufficiently small, then you've got equality.

这篇关于使用==运算符比较两个舍入浮点数是正确的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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