exp()函数 快速算法实现

来源:互联网 发布:jisucopy什么软件 编辑:程序博客网 时间:2024/05/09 07:23

Using Faster Exponential Approximation


In some scenarios/applicatons, where the precision may not be so critically important but the speed (performance) is, you may be willing to sacrifice some extent of accuracy for the speed.

In neutral networks, where the math function e^n  where is usually small (less than 2, for instance), you can avoid the expensive exp() provided by math.h (for other programming languages, similar inbuilt system functions are provided)

The e^x  (exponential function) can be considered as the following:

Using Faster Exp Approximation (Exponential function)

In practice,  cannot approach to the infinity but we can achieve a relatively good accuracy by using a large n.

For example, if we put n = 256 , then we can multiply 1 + 1/256  by itself 8 times due to the fact x^{256} = {x^2}^{128} = {{x^2}^{2}}^{64} \dots

With this in mind, we can come up with the following approximation:

inlinedouble exp1(double x) {  x = 1.0 + x / 256.0;  x *= x; x *= x; x *= x; x *= x;  x *= x; x *= x; x *= x; x *= x;  return x;}

We can also multiply a few more times, to increase the accuracy.

inlinedouble exp2(double x) {  x = 1.0 + x / 1024;  x *= x; x *= x; x *= x; x *= x;  x *= x; x *= x; x *= x; x *= x;  x *= x; x *= x;  return x;}

Now, you have the pattern, but for now, we need to test how accurate these approximations are:

Using Faster Exp Approximation (Exponential function)

The above plots 3 curves, which are the exp provided by math.h, the exp 256 and the exp 1024. They show very good agreement for input smaller than 5.

We plot the difference to make it easier to see.

Using Faster Exp Approximation (Exponential function)

Wow, it really can be a faster alternative if the required input range smaller than 5. For negative inputs, the difference won’t be so noticeable because the value itself is so tiny that can’t be observed visually in graph.

The exp 256 is 360 times faster than the traditional exp and the exp 1024 is 330 times faster than the traditional exp.

0 0
原创粉丝点击