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

โปรแกรม C++ คำนวณ Discrete Fourier Transform แบบ Naive


ใน Discrete Fourier Transform (DFT) รายการจำกัดของตัวอย่างที่ห่างกันเท่าๆ กันของฟังก์ชัน จะถูกแปลงเป็นรายการ係数ของการรวมซึ่งมีค่า sinusoids 複素数จำกัด พวกมันเรียงตามความถี่ ที่มีค่าตัวอย่างเดียวกัน เพื่อแปลงฟังก์ชันที่ตัวอย่างแล้วจากโดเมนต้นฉบับ (มักเป็นเวลาหรือตำแหน่งตามเส้น) ไปยังโดเมนความถี่

อัลกอริทึม

Begin
    ประกาศตัวแปร M และกำหนดค่าเป็นจำนวนเต็มบางค่า
    ประกาศอาร์เรย์ function[M]
    For i = 0 ถึง M-1 ทำ
        function[i] = (((a * (double) i) + (b * (double) i)) - c)
    จบ for
    ประกาศฟังก์ชัน sine[M]
    ประกาศฟังก์ชัน cosine[M]
    for i = 0 ถึง M-1 ทำ
        cosine[i] = cos((2 * i * k * PI) / M)
        sine[i] = sin((2 * i * k * PI) / M)
    จบ for
    ประกาศ DFT_Coeff dft_value[k]
    for j = 0 ถึง k-1 ทำ
        for i = 0 ถึง M-1 ทำ
            dft_value.real += function[i] * cosine[i]
            dft_value.img += function[i] * sine[i]
        จบ for
    จบ for
    พิมพ์ค่า
End

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

#include <iostream>
#include <math.h>
using namespace std;

#define PI 3.14159265

class DFT_Coeff {
    public:
    double real, img;
    DFT_Coeff() {
        real = 0.0;
        img = 0.0;
    }
};

int main(int argc, char **argv) {
    int M = 10;
    cout << "Enter the coefficient of simple linear function:\n";
    cout << "ax + by = c\n";
    double a, b, c;
    cin >> a >> b >> c;
    
    double function[M];
    for (int i = 0; i < M; i++) {
        function[i] = (((a * (double) i) + (b * (double) i)) - c);
    }
    
    cout << "Enter the max K value: ";
    int k;
    cin >> k;
    
    double cosine[M];
    double sine[M];
    for (int i = 0; i < M; i++) {
        cosine[i] = cos((2 * i * k * PI) / M);
        sine[i] = sin((2 * i * k * PI) / M);
    }
    
    DFT_Coeff dft_value[k];
    cout << "The coefficients are: ";
    for (int j = 0; j < k; j++) {
        for (int i = 0; i < M; i++) {
            dft_value[j].real += function[i] * cosine[i];
            dft_value[j].img += function[i] * sine[i];
        }
        cout << "(" << dft_value[j].real << ") - " << "(" << dft_value[j].img << " i)\n";
    }
}

ผลลัพธ์

Enter the coefficient of simple linear function:
ax + by = c
4 5 6
Enter the max K value: 10
The coefficients are:
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)
(345) - (-1.64772e-05 i)