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

โปรแกรม C++ คำนวณ DFT Coefficients โดยตรง


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

อัลกอริทึม

Begin
    ประกาศตัวแปรสามตัวคือสัมประสิทธิ์สมการเชิงเส้นและค่าสูงสุด
    อ่านตัวแปร
    กำหนดคลาสมีตัวแปร real, img
    สร้าง constructor ตั้งค่า real, img เป็นศูนย์
    ประกาศตัวแปร M และกำหนดค่าเป็นจำนวนเต็มบางค่า
    สร้าง function[M]
    For i=0 ถึง M ทำ
        function[i] = (((a * (double) i) + (b * (double) i)) - c)
    จบ for
    ประกาศฟังก์ชัน sine[M]
    ประกาศฟังก์ชัน cosine[M]
    for i = 0 ถึง M ทำ
        cosine[i] = cos((2 * i * k * PI) / M)
        sine[i] = sin((2 * i * k * PI) / M)
    จบ for
    for i = 0 ถึง M ทำ
        dft_value.real += function[i] * cosine[i]
        dft_value.img += function[i] * sine[i]
    จบ 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 coeff 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;
    cout << "The coeffs are: ";
    for (int i = 0; i < M; i++) {
        dft_value.real += function[i] * cosine[i];
        dft_value.img += function[i] * sine[i];
    }
    cout << "(" << dft_value.real << ") - " << "(" << dft_value.img << " i)";
}

ผลลัพธ์

Enter the coeff of simple linear function:
ax + by = c
4 6 7
Enter the max K value: 4
The coeffs are: (-50) - (-16.246 i)