]> git.mxchange.org Git - simgear.git/blob - simgear/math/fastmath.hxx
Ignore generated binaries.
[simgear.git] / simgear / math / fastmath.hxx
1 /*
2  * \file fastmath.hxx
3  * fast mathematics routines.
4  *
5  * Refferences:
6  *
7  * A Fast, Compact Approximation of the Exponential Function
8  * Nicol N. Schraudolph
9  * IDSIA, Lugano, Switzerland
10  * http://www.inf.ethz.ch/~schraudo/pubs/exp.pdf
11  *
12  * Fast log() Function, by Laurent de Soras:
13  * http://www.flipcode.com/cgi-bin/msg.cgi?showThread=Tip-Fastlogfunction&forum=totd&id=-1
14  *
15  */
16
17 /*
18  * $Id$
19  */
20
21 #ifndef _SG_FMATH_HXX
22 #define _SG_FMATH_HXX 1
23
24 #ifndef __cplusplus
25 # error This library requires C++
26 #endif
27
28 #include <math.h>
29
30
31 double fast_exp(double val);
32 double fast_exp2(const double val);
33
34 float fast_pow(const float val1, const float val2);
35 float fast_log2(const float cal);
36 float fast_root(const float f, const int n);
37
38 float _fast_pow2(const float cal);
39 float _fast_log2(const float val);
40
41 float fast_sin(const float val);
42 float fast_cos(const float val);
43 float fast_tan(const float val);
44 float fast_asin(const float val);
45 float fast_acos(const float val);
46 float fast_atan(const float val);
47
48 void fast_BSL(float &x, register unsigned long shiftAmount);
49 void fast_BSR(float &x, register unsigned long shiftAmount);
50
51
52 inline float fast_log2 (float val)
53 {
54     union {
55         float f;
56         int i;
57     } v;
58     v.f = val;
59     const int log_2 = ((v.i >> 23) & 255) - 128;
60     v.i &= ~(255 << 23);
61     v.i += 127 << 23;
62
63     v.f = ((-1.0f/3) * v.f + 2) * v.f - 2.0f/3;   // (1)
64
65     return (v.f + log_2);
66 }
67
68
69 /**
70  * This function is about 3 times faster than the system log() function
71  * and has an error of about 0.01%
72  */
73 inline float fast_log (const float &val)
74 {
75    return (fast_log2 (val) * 0.69314718f);
76 }
77
78 inline float fast_log10 (const float &val)
79 {
80    return (fast_log2(val) / 3.321928095f);
81 }
82
83
84 /**
85  * This function is about twice as fast as the system pow(x,y) function
86  */
87 inline float fast_pow(const float val1, const float val2)
88 {
89    return _fast_pow2(val2 * _fast_log2(val1));
90 }
91
92
93 /*
94  * Haven't seen this elsewhere, probably because it is too obvious?
95  * Anyway, these functions are intended for 32-bit floating point numbers
96  * only and should work a bit faster than the regular ones.
97  */
98 inline float fast_abs(float f)
99 {
100     int i=((*(int*)&f)&0x7fffffff);
101     return (*(float*)&i);
102 }
103
104 inline float fast_neg(float f)
105 {
106     int i=((*(int*)&f)^0x80000000);
107     return (*(float*)&i);
108 }
109
110 inline int fast_sgn(float f)
111 {
112     return 1+(((*(int*)&f)>>31)<<1);
113 }
114
115 #endif // !_SG_FMATH_HXX
116