c/c++语言开发共享各种浮动值的epsilon

FLT_MIN常量最接近零。 如何获得最接近some number数值?

举个例子:

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

我更喜欢不使用特殊function的数字公式。

    警告:在处理另一个答案时,在此代码中发现了错误。 我希望稍后更新。 与此同时,它失败了一些涉及次正规的值。

    C在头文件中为此提供了一个函数。 nextafterf(x, INFINITY)x之后的下一个可表示的值,朝向INFINITY的方向。

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

    假设IEEE 754,以下内容返回您寻找的epsilon,单精度(浮点)。

     #include  #include  /* 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)); } 

    以下内容返回传递值后浮点数中可表示的下一个值(将-0和+ 0视为相同)。

     #include  #include  /* 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); } 

      以上就是c/c++开发分享各种浮动值的epsilon相关内容,想了解更多C/C++开发(异常处理)及C/C++游戏开发关注计算机技术网(www.ctvol.com)!)。

      本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

      ctvol管理联系方式QQ:251552304

      本文章地址:https://www.ctvol.com/c-cdevelopment/568971.html

      (0)
      上一篇 2021年2月24日
      下一篇 2021年2月24日

      精彩推荐