使用常用数学函数exp()log()时如何防止溢出?

Wil*_*ing 8 c c++ undefined-behavior

一切都在标题中.使用exp()和log()两个函数时如何检查可能的溢出?

gif*_*gkp 12

#include <errno.h>
Run Code Online (Sandbox Code Playgroud)

当发生一个流量时,则errno设置为ERANGE.


下次,在问之前做好功课.

谷歌搜索:"c ++ exp"将此作为第一个结果返回http://www.cplusplus.com/reference/cmath/exp/
在页面中间,您正在寻找什么.

  • @ user2114690我想我理解你的担心.但是`<cmath>`中的一个函数溢出是_not_未定义的行为,所以你不必担心预先避免它; 检查后是安全和充分的. (3认同)
  • 它比你想象的容易.试试,如果errno设置为ERANGE,请尝试使用不同的值.这种方法*简单*,*便宜*而且*有效*. (2认同)

Dav*_*eri 7

要扩展@TheOtherGuy的答案,可以在发生溢出时取消操作.

#include <stdio.h>
#include <math.h>
#include <errno.h>

int main(void)
{
    double param, result;

    errno = 0;
    param = 1e3;
    result = exp (param);
    if (errno == ERANGE) {
        printf("exp(%f) overflows\n", param);
        result = param;
    }
    printf ("The exponential value of %f is %f.\n", param, result );
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

  • @ user2114690对于提供IEEE 754浮点运算的编译平台,没有必要测试溢出的参数,因为当`exp(param)`太大而无法表示时,它会产生IEEE 754值`+ inf`并且不会导致未定义的行为.第199333号问题涉及整数溢出,不适用于IEEE 754浮点实现. (3认同)
  • 请注意,通常,在调用函数之前需要将"errno"设置为0才能获得有意义的结果.这个简单的例子是有效的,因为`errno`在启动时是0,但**任何**库函数都允许设置`errno`,所以在调用`exp`之后看到`ERANGE`不**表示`exp`除非在调用`exp`之前将`errno`设置为0,否则设置它. (2认同)