在CoreGraphics中的浮动比较(平等) [英] Float comparison (equality) in CoreGraphics

查看:148
本文介绍了在CoreGraphics中的浮动比较(平等)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple CoreGraphics.framework CGGeometry.h

CG_INLINE bool __CGSizeEqualToSize(CGSize size1, CGSize size2)
{
    return size1.width == size2.width && size1.height == size2.height;
}
#define CGSizeEqualToSize __CGSizeEqualToSize

为什么与 == ?我不能相信这是一个错误。那么你能解释一下吗?
(我想要的东西像 fabs(size1.width - size2.width)< 0.001 )。

Why do they (Apple) compare floats with ==? I can't believe this is a mistake. So can you explain me? (I've expected something like fabs(size1.width - size2.width) < 0.001).

推荐答案

浮点比较是所有OSX和iOS体系结构的本地宽度。

Floating point comparisons are native width on all OSX and iOS architectures.

对于 float ,即:

i386,x86_64:


  • 使用 ucomiss 系列中的说明,32位XMM寄存器(或第二个操作数的存储器)

  • $ c>

  • 32 bit XMM register (or memory for second operand)
  • using an instructions in the family of ucomiss

ARM:


  • 32位寄存器

  • 使用与 vcmp
  • 相同的系列中的说明
  • 32 bit register
  • using instructions in the same family as vcmp

通过将这些类型的存储限制为32/64,一些浮点数比较问题已被删除。其他平台可能经常使用本地80位FPU(示例)。在OS X上,SSE指令是有利的,并且它们使用自然宽度。因此,这减少了很多浮点比较问题。

Some of the floating point comparison issues have been removed by restricting storage to 32/64 for these types. Other platforms may use the native 80 bit FPU often (example). On OS X, SSE instructions are favored, and they use natural widths. So, that reduces many of the floating point comparison issues.

但是仍然有错误的空间,或者你会喜欢近似的时间。关于CGGeometry类型值的一个隐藏的细节是它们可以被四舍五入为一个附近的整数(在某些情况下你可能想要自己这样做)。

But there is still room for error, or times when you will favor approximation. One hidden detail about CGGeometry types' values is that they may be rounded to a nearby integer (you may want to do this yourself in some cases).

CGFloat( float double -x86_64)和典型值,合理假设舍入值通常足够准确,使得结果在大多数情况下将是适当地可比较的。因此,在这些限制之内,它是非常安全,相当准确和相当快。

Given the range of CGFloat (float or double-x86_64) and typical values, it's reasonable to assume the rounded values generally be represented accurately enough, such that the results will be suitably comparable in the majority of cases. Therefore, it's "pretty safe", "pretty accurate", and "pretty fast" within those confines.

还有时候你可能喜欢几何计算中的近似比较,但是苹果的实现是我认为最接近这个上下文中的通用解决方案的参考实现。

There are still times when you may prefer approximated comparisons in geometry calculations, but apple's implementation is what I'd consider the closest to a reference implementation for the general purpose solution in this context.

这篇关于在CoreGraphics中的浮动比较(平等)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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