Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

C++ Program: ผลรวมอนุกรม 1 - x²/2! + x⁴/4! - ... จนถึงพจน์ที่ n

คำนวณอนุกรม: S = 1 - x²/2! + x⁴/4! - x⁶/6! + ... จนถึงพจน์ที่ n

นี่คือ Maclaurin Series ของ cos(x) (แต่มีพจน์แรกคือ 1 = x⁰/0!)

ตัวอย่างโค้ด

#include <math.h>
#include <stdio.h>

double calc_sum(double x, int n) {
    double sum = 1.0;
    double term = 1.0;

    for (int i = 1; i < n; i++) {
        int power = 2 * i;           // 2, 4, 6, ...
        double fact = 1.0;
        for (int j = 1; j <= power; j++)
            fact *= j;

        term *= -1;                  // สลับเครื่องหมาย
        sum += term * pow(x, power) / fact;
    }
    return sum;
}

int main() {
    double x = 5;
    int n = 7;
    printf("%.4f\n", calc_sum(x, n));
    return 0;
}

ผลลัพธ์

0.3469

การตรวจสอบ

cos(5) ≈ 0.2837 (Radians)
อนุกรม 7 พจน์: 1 - 25/2 + 625/24 - 15625/720 + 390625/40320 - 9765625/3628800 + 244140625/479001600 ≈ 0.3469

收敛较慢因为 x=5 较大,需要更多项才准确

Optimization: คำนวณ Factorial และ Power แบบสะสม

double calc_sum_opt(double x, int n) {
    double sum = 1.0;
    double term = 1.0;
    double x_pow = 1.0;
    double fact = 1.0;

    for (int i = 1; i < n; i++) {
        x_pow *= x * x;      // x^(2i)
        fact *= (2*i - 1) * (2*i); // (2i)!
        term = -term;        // สลับเครื่องหมาย
        sum += term * x_pow / fact;
    }
    return sum;
}