]> git.mxchange.org Git - simgear.git/blob - simgear/math/fastmath.hxx
Don't bother other develoers with problems caused by MipsPro (version < 7.3) compilers
[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 #ifdef _MSC_VER
29 #define  _USE_MATH_DEFINES
30 #endif
31 #include <math.h>
32
33
34 double fast_exp(double val);
35
36 void fast_BSL(float &x, register unsigned long shiftAmount);
37 void fast_BSR(float &x, register unsigned long shiftAmount);
38
39 inline float fast_log2 (float val)
40 {
41    int * const    exp_ptr = reinterpret_cast <int *> (&val);
42    int            x = *exp_ptr;
43    const int      log_2 = ((x >> 23) & 255) - 128;
44    x &= ~(255 << 23);
45    x += 127 << 23;
46    *exp_ptr = x;
47
48    val = ((-1.0f/3) * val + 2) * val - 2.0f/3;   // (1)
49
50    return (val + log_2);
51 }
52
53 /**
54  * This function is about 3 times faster than the system log() function
55  * and has an error of about 0.01%
56  */
57 inline float fast_log (const float &val)
58 {
59    return (fast_log2 (val) * 0.69314718f);
60 }
61
62 inline float fast_log10 (const float &val)
63 {
64    return (fast_log2(val) / 3.321928095f);
65 }
66
67
68 #endif // !_SG_FMATH_HXX
69