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, notx(that's the sine series!). Your initial setup hascos = 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 from0. Without reducingxto 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
- Period Reduction:
- We use
fmod()to wrapxinto 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.
- We use
- 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.
- The cosine Taylor series is:
- Robust Loop:
- Using a loop up to 20 iterations is more than enough for double-precision accuracy once
xis in the reduced interval.
- Using a loop up to 20 iterations is more than enough for double-precision accuracy once
Testing the Fix
- For small values:
coseno(0.5)should return ~0.87758, which matches the standardcos()function. - For large values:
coseno(1000.0)should return the same ascos(1000.0)(since we've reduced the angle to the correct periodic interval).
内容的提问来源于stack exchange,提问作者Juan Jo Murillo
相关产品推荐
相关产品推荐

