Fast sigmoid algorithm

后端 未结 11 1878
庸人自扰
庸人自扰 2020-12-12 15:55

The sigmoid function is defined as

I found that using the C built-in function exp() to calculate the value of f(x) is slow. Is th

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-12 16:36

    It's best to measure on your hardware first. Just a quick benchmark script shows, that on my machine 1/(1+|x|) is the fastest, and tanh(x) is the close second. Error function erf is pretty fast too.

    % gcc -Wall -O2 -lm -o sigmoid-bench{,.c} -std=c99 && ./sigmoid-bench
    atan(pi*x/2)*2/pi   24.1 ns
    atan(x)             23.0 ns
    1/(1+exp(-x))       20.4 ns
    1/sqrt(1+x^2)       13.4 ns
    erf(sqrt(pi)*x/2)    6.7 ns
    tanh(x)              5.5 ns
    x/(1+|x|)            5.5 ns
    

    I expect that the results may vary depending on architecture and the compiler used, but erf(x) (since C99), tanh(x) and x/(1.0+fabs(x)) are likely to be the fast performers.

提交回复
热议问题