簡體   English   中英

簡單三角函數計算定點數的sin()和cos()

[英]Simple trigonometric algorithm to compute sin() and cos() of fixed-point numbers

正如我在其他問題中所展示的那樣,我目前正在實現一個C ++元編程庫,該庫除其他外還包括一組用於編譯時算術的類型和元函數。

我現在的目標是為我的定點類型實現三角函數sincos
我的問題是,我發現的關於三角算法的每篇論文都談到了CORDIC或某種泰勒級數。 CORDIC的問題在於,它需要通過查找表來提供大量的預先計算的值,而我不能輕易將tmp提供給它。 另外,CORDIC的要點是在沒有乘法器的硬件中計算該三角函數,我完全可以與我的庫進行乘法運算。

所以我的問題是: 除了CORDIC和泰勒級數之外,還有其他簡單的替代方法可以計算三角函數嗎?

最終,我通過泰勒級數實現了sin元函數,默認情況下使用10個術語系列(可以配置)。 我的實現基於這篇有趣的文章

我的庫包括使用迭代器的tmp for循環的實現,以及允許以“清晰”方式編寫復雜表達式的表達式模板 (與常用模板元編程語法add<mul<sub<1,2>>>相比,該表達式更清晰) add<mul<sub<1,2>>> ...)。 這使我可以從字面上復制粘貼該文章提供的C實現:

template<typename T , typename TERMS_COUNT = mpl::uinteger<4>>
struct sin_t;

template<typename T , typename TERMS_COUNT = mpl::uinteger<4>>
using sin = typename sin_t<T,TERMS_COUNT>::result;

/*
 * sin() function implementation through Taylor series (Check http://www10.informatik.uni-erlangen.de/~pflaum/pflaum/ProSeminar/meta-art.html)
 * 
 * The C equivalent code is:
 * 
 * // Calculate sin(x) using j terms
 * float sine(float x, int j)
 * {
 *     float val = 1;
 *
 *     for (int k = j - 1; k >= 0; --k)
 *         val = 1 - x*x/(2*k+2)/(2*k+3)*val;
 *
 *     return x * val;
 * }
 */

template<mpl::fpbits BITS , mpl::fbcount PRECISION , unsigned int TERMS_COUNT>
struct sin_t<mpl::fixed_point<BITS,PRECISION>,mpl::uinteger<TERMS_COUNT>>
{
private:
    using x = mpl::fixed_point<BITS,PRECISION>;

    using begin = mpl::make_integer_backward_iterator<TERMS_COUNT-1>;
    using end   = mpl::make_integer_backward_iterator<-1>;

    using one   = mpl::decimal<1,0,PRECISION>;
    using two   = mpl::decimal<2,0,PRECISION>;
    using three = mpl::decimal<3,0,PRECISION>;

    template<typename K , typename VAL>
    struct kernel : public mpl::function<decltype( one() - ( x() * x() )/(two() * K() + two())/(two()*K()+three())*VAL() )> {};

public:
    using result = decltype( x() * mpl::for_loop<begin , end , one , kernel>() );
};

是項目存儲庫中實現的標頭。

通過查找表的大量預計算值

“巨大”是多少? 聽起來像是一次性的工作,一旦完成,它就會像地獄一樣快。 我的建議? 拿鐵鏟填寫表格。 您將在這里得到另一個答案的時候就完成了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM