You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中无数学函数实现余弦函数:泰勒级数仅小数值正确问题咨询

Fixing Your Taylor Series Cosine Implementation

Let's break down why your code only works for small values, and fix it step by step:

Key Issues in the Original Code

  • Incorrect Taylor Series Initialization: The cosine Taylor series starts with 1, not x (that's the sine series!). Your initial setup has cos = t = x, which immediately throws off all calculations even for small values (you might have noticed it returns values close to sine instead of cosine for tiny inputs).
  • No Period Reduction: Cosine is periodic with 2π, and the Taylor series converges very slowly (or not at all) for values far from 0. Without reducing x to a small interval like [-π, π], large inputs will never give accurate results, even with 20 iterations.
  • Loop Logic Misalignment: The iteration steps don't properly map to the terms of the cosine series once the initial term is wrong.

Corrected Implementation

#include <math.h> // For fmod() and M_PI

double coseno(float x) {
    // Step 1: Reduce x to the interval [-π, π] using periodicity
    double rad = fmod((double)x, 2 * M_PI);
    if (rad > M_PI) {
        rad -= 2 * M_PI;
    } else if (rad < -M_PI) {
        rad += 2 * M_PI;
    }

    // Step 2: Initialize Taylor series correctly
    double cos_val = 1.0; // First term of cosine series
    double term = 1.0;    // Tracks the current term, starts with the 0th term
    int n = 1;

    // Step 3: Iterate to compute subsequent terms
    while (n <= 20) {
        // Calculate the next term: term *= (-rad²) / ((2n-1)*2n)
        term *= (-rad * rad) / ((2 * n - 1) * (2 * n));
        cos_val += term;
        n++;
    }

    return cos_val;
}

What Changed & Why

  1. Period Reduction:
    • We use fmod() to wrap x into the range [0, 2π], then adjust to [-π, π] to keep values as close to 0 as possible. This ensures the Taylor series converges quickly even for large inputs.
  2. Proper Series Initialization:
    • The cosine Taylor series is:

      cos(x) = 1 - x²/2! + x⁴/4! - x⁶/6! + ... + (-1)^n x^(2n)/(2n)! + ...

    • Starting with cos_val = 1.0 (the 0th term) and building each subsequent term by multiplying the previous term by -x²/((2n-1)(2n)) avoids recalculating factorials from scratch, which is more efficient and less error-prone.
  3. Robust Loop:
    • Using a loop up to 20 iterations is more than enough for double-precision accuracy once x is in the reduced interval.

Testing the Fix

  • For small values: coseno(0.5) should return ~0.87758, which matches the standard cos() function.
  • For large values: coseno(1000.0) should return the same as cos(1000.0) (since we've reduced the angle to the correct periodic interval).

内容的提问来源于stack exchange,提问作者Juan Jo Murillo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:04:10