Fastest implementation of sine, cosine and square root in C++ (doesn't need to be much accurate)

前端 未结 15 2009
执笔经年
执笔经年 2020-12-04 10:55

I am googling the question for past hour, but there are only points to Taylor Series or some sample code that is either too slow or does not compile at all. Well, most answe

15条回答
  •  悲&欢浪女
    2020-12-04 11:39

    QT has fast implementations of sine (qFastSin) and cosine (qFastCos) that uses look up table with interpolation. I'm using it in my code and they are faster than std:sin/cos and precise enough for what I need:

    https://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmath.h.html#_Z8qFastSind

    #define QT_SINE_TABLE_SIZE 256
    
    
    inline qreal qFastSin(qreal x)
    {
       int si = int(x * (0.5 * QT_SINE_TABLE_SIZE / M_PI)); // Would be more accurate with qRound, but slower.
       qreal d = x - si * (2.0 * M_PI / QT_SINE_TABLE_SIZE);
       int ci = si + QT_SINE_TABLE_SIZE / 4;
       si &= QT_SINE_TABLE_SIZE - 1;
       ci &= QT_SINE_TABLE_SIZE - 1;
       return qt_sine_table[si] + (qt_sine_table[ci] - 0.5 * qt_sine_table[si] * d) * d;
    }
    
    inline qreal qFastCos(qreal x)
    {
       int ci = int(x * (0.5 * QT_SINE_TABLE_SIZE / M_PI)); // Would be more accurate with qRound, but slower.
       qreal d = x - ci * (2.0 * M_PI / QT_SINE_TABLE_SIZE);
       int si = ci + QT_SINE_TABLE_SIZE / 4;
       si &= QT_SINE_TABLE_SIZE - 1;
       ci &= QT_SINE_TABLE_SIZE - 1;
       return qt_sine_table[si] - (qt_sine_table[ci] + 0.5 * qt_sine_table[si] * d) * d;
    }
    

    The LUT and license can be found here: https://code.woboq.org/qt5/qtbase/src/corelib/kernel/qmath.cpp.html#qt_sine_table

    These pair of functions take radian inputs. The LUT covers the entire 2π input range. The function interpolates between values using the difference d, using the cosine (with a similar interpolation using sine again) as the derivative.

提交回复
热议问题