它是正确的来比较两个圆形的使用==操作符浮点数? [英] Is it correct to compare two rounded floating point numbers using the == operator?

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

问题描述

还是有机会的操作会失败?

Or is there a chance that the operation will fail?

感谢。

我选择了错误的期限和我真正的意思是四舍五入为0,而不是被截断。

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

的一点是,我需要的两个双打的整数部分比较,我只是他们铸造成int,然后用==,但是,正如有人指出的,在我前面的问题之一,这可能会引发溢出异常,如果双重不能融入整数。

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.

所以现在的问题是是否正确使用==操作符来比较两个双打有previously被四舍五入为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 a site which discusses the pros and cons of several methods of comparing floating point numbers.

我会跟去的方法是相对误差的方法。发现这两个数字之间的差值,将其转换成数字的百分比,并且如果该百分比是足够小,则你已经得到平等

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天全站免登陆