简单的三角函数算法,用于计算定点数的 sin() 和 cos()

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

本文关键字:sin cos 定点数 计算 三角函数 算法 用于 简单      更新时间:2023-10-16

正如我在其他问题中所展示的,我目前正在实现一个C++元编程库,其中包括一组用于编译时算术的类型和元函数。

我现在的目标是为我的不动点类型实现三角函数sincos
我的问题是,我找到的每篇关于三角算法的论文都谈到了CORDIC或某种泰勒级数。CORDIC 的问题在于它需要通过查找表预先计算出大量值,而我无法轻松地为 tmp 提供它。此外,CORDIC 的重点是计算没有乘法器的硬件中的三角函数,我完全可以使用我的库进行乘法。

所以我的问题是:除了CORDIC和泰勒级数之外,还有其他简单的替代方案来计算三角函数吗?

最后,

我通过泰勒级数实现了sin元函数,默认使用 10 个项的系列(可配置)。我在这篇有趣的文章中基于我的实现。

我的库包括使用迭代器和表达式模板的 tmp for 循环的实现,以允许以"清晰"的方式编写复杂的表达式(与常见的模板元编程语法相比清晰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>() );
};

下面是项目存储库中实现的标头。

通过查找表预先计算的大量值集

有多少是"巨大的"? 听起来像是一次性的努力,一旦你完成,就会像地狱一样快。 我的建议? 拿一把铲子,把那张桌子填满。 当你在这里得到另一个答案时,你已经完成了它。