浮点相等和公差

Floating point equality and tolerances(浮点相等和公差)
本文介绍了浮点相等和公差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

a_float == b_float 之类的东西比较两个浮点数是在找麻烦,因为 a_float/3.0 * 3.0 可能不等于 a_float 由于舍入错误.

Comparing two floating point number by something like a_float == b_float is looking for trouble since a_float / 3.0 * 3.0 might not be equal to a_float due to round off error.

通常的做法是 fabs(a_float - b_float) <tol.

如何计算tol?

理想情况下,容差应该刚好大于一两个最低有效数字的值.因此,如果使用单精度浮点数 tol = 10E-6 应该是正确的.然而,这不适用于 a_float 可能非常小或可能非常大的一般情况.

Ideally tolerance should be just larger than the value of one or two of the least significant figures. So if the single precision floating point number is use tol = 10E-6 should be about right. However this does not work well for the general case where a_float might be very small or might be very large.

如何为所有一般情况正确计算 tol?我特别对 C 或 C++ 案例感兴趣.

How does one calculate tol correctly for all general cases? I am interested in C or C++ cases specifically.

推荐答案

这篇博文包含一个例子,相当简单的实现,以及背后的详细理论http://randomascii.wordpress.com/2012/02/25/比较浮点数-2012 版/它也是系列之一,因此您可以随时阅读更多内容.简而言之:对大多数数字使用 ULP,对接近零的数字使用 epsilon,但仍有一些注意事项.如果您想确定您的浮点数学,我建议您阅读整个系列.

This blogpost contains an example, fairly foolproof implementation, and detailed theory behind it http://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/ it is also one of a series, so you can always read more. In short: use ULP for most numbers, use epsilon for numbers near zero, but there are still caveats. If you want to be sure about your floating point math i recommend reading whole series.

这篇关于浮点相等和公差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)