如何让泰勒级数余弦函数处理更大的角度

问题描述 投票:0回答:0

我已经基于泰勒级数实现了我自己的余弦函数,看起来它不能很好地处理大于 pi 的角度。这是我的实现:

#include <cmath>
#include <iostream>

static constexpr float PI_F32 = static_cast<float>(M_PI);
constexpr float mod(float x, float y)
{
    return (x - (int(x / y) * y));
}
constexpr float Cosine(float radians) 
{
    const float x = mod(fabsf(radians), float(2.f * PI_F32));
    const float x2 = x * x;

    constexpr float c2 = 1.f / 24.f;
    constexpr float c3 = -1.f / 720.f;
    constexpr float c4 = 1.f / 40320.f;
    constexpr float c5 = -1.f / 3628800.f;

    return 1.f - (x2 * 0.5f) + (x2 * (x2 * c2 + x2 * (x2 * c3 + x2 * (x2 * c4 + x2 * x2 * c5))));
}
int main() 
{
    static constexpr float x = 3.5f * PI_F32;
    printf("standard: %0.9f\n", cosf(x));
    printf("my version: %0.9f\n", Cosine(x));
    return 0;
}

输出

standard: 0.000000664
my version: -0.222440109

我想只有 5 个学期,做一个

mod
出于某种原因无济于事。我在某处读到此实现仅适用于 [-pi, pi] 范围内的角度。我想知道如何在该范围内适应更大的角度。我找不到任何解决方案,如果已经有答案,请在评论中链接它。

c++ trigonometry taylor-series
© www.soinside.com 2019 - 2024. All rights reserved.