各种浮点值的epsilon [英] epsilon for various float values

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

问题描述

有一个FLT_MIN常数,该常数最接近零.如何最接近some number值?

There is FLT_MIN constant that is nearest to zero. How to get nearest to some number value?

例如:

float nearest_to_1000 = 1000.0f + epsilon;
// epsilon must be the smallest value satisfying condition:
// nearest_to_1000 > 1000.0f

我希望在不使用特殊功能的情况下使用数字公式.

I would prefer numeric formula without using special functions.

推荐答案

警告:在尝试另一个答案时,在此代码中发现了错误.我希望以后再更新.同时,对于某些涉及次法线的值,它会失败.

C在<math.h>标头中为此提供了一个功能. nextafterf(x, INFINITY)x之后的下一个可表示值,朝着INFINITY的方向.

C provides a function for this, in the <math.h> header. nextafterf(x, INFINITY) is the next representable value after x, in the direction toward INFINITY.

但是,如果您愿意自己做:

However, if you'd prefer to do it yourself:

以下内容假设IEEE 754,以单精度(浮点数)返回您要查找的epsilon.

The following returns the epsilon you seek, for single precision (float), assuming IEEE 754.

#include <float.h>
#include <math.h>


/*  Return the ULP of q.

    This was inspired by Algorithm 3.5 in Siegfried M. Rump, Takeshi Ogita, and
    Shin'ichi Oishi, "Accurate Floating-Point Summation", _Technical Report
    05.12_, Faculty for Information and Communication Sciences, Hamburg
    University of Technology, November 13, 2005.
*/
float ULP(float q)
{
    // SmallestPositive is the smallest positive floating-point number.
    static const float SmallestPositive = FLT_EPSILON * FLT_MIN;

    /*  Scale is .75 ULP, so multiplying it by any significand in [1, 2) yields
        something in [.75 ULP, 1.5 ULP) (even with rounding).
    */
    static const float Scale = 0.75 * FLT_EPSILON;

    q = fabs(q);

    return fmax(SmallestPositive, q - (q - q * Scale));
}

下面的值返回传递值后在float中可表示的下一个值(将-0和+0相同).

The following returns the next value representable in float after the value it is passed (treating -0 and +0 as the same).

#include <float.h>
#include <math.h>


/*  Return the next floating-point value after the finite value q.

    This was inspired by Algorithm 3.5 in Siegfried M. Rump, Takeshi Ogita, and
    Shin'ichi Oishi, "Accurate Floating-Point Summation", _Technical Report
    05.12_, Faculty for Information and Communication Sciences, Hamburg
    University of Technology, November 13, 2005.
*/
float NextAfter(float q)
{
    // SmallestPositive is the smallest positive floating-point number.
    static const float SmallestPositive = FLT_EPSILON * FLT_MIN;

    /*  Scale is .625 ULP, so multiplying it by any significand in [1, 2)
        yields something in [.625 ULP, 1.25 ULP].
    */
    static const float Scale = 0.625 * FLT_EPSILON;

    return q + fmax(SmallestPositive, fabs(q)*Scale);
}

这篇关于各种浮点值的epsilon的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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