fork download
  1. #include<iostream>
  2. #include<iomanip>
  3. #include<cmath>
  4. #include <cstdlib>
  5. using namespace std;
  6.  
  7.  
  8. #define mu 0.2f //convergence rate
  9. #define M 5 //order of filter
  10. #define I 1000 //number of samples
  11.  
  12. double Input[I] = { 0.0 };
  13. double Desired[I] = { 0.0 };
  14.  
  15. //double H[M] = { 1, 0.5, 0.25, 0.125, 0.0625 }; //the main system
  16.  
  17. double H[M] = { 0.0625, 0.125, 0.25, 0.5, 1 }; //we need inverse of main system to convolution
  18.  
  19.  
  20.  
  21. void initialize()
  22. {
  23. for (int i = 0; i < I; i++)
  24. Input[i] = rand() / (float)RAND_MAX;
  25.  
  26. for (int i = 0; i < I; i++)
  27. for (int j = 0; j < M; j++)
  28. if (i - j >= 0)
  29. Desired[i] += Input[i - j] * H[j];
  30. }
  31.  
  32. int main()
  33. {
  34. initialize();
  35.  
  36. long T, n = 0;
  37. double D, Y, E;
  38. double W[M] = { 0.0 };
  39. double X[M] = { 0.0 };
  40.  
  41. FILE *Y_out=NULL, *error=NULL, *weights=NULL;
  42.  
  43.  
  44. #define _CRT_NONSTDC_NO_WARNINGS Y_out = fopen("Y_OUT", "w++"); //file for output samples
  45.  
  46. #define _CRT_NONSTDC_NO_WARNINGS error = fopen("ERROR", "w++"); //file for error samples
  47.  
  48. #define _CRT_NONSTDC_NO_WARNINGS weights = fopen("WEIGHTS", "w++"); //file for weights samples
  49.  
  50.  
  51.  
  52. for (T = 0; T < I; T++)
  53. {
  54. for (int m = T; m > T - M; m--) {
  55. if (m >= 0)
  56. X[M + (m - T) - 1] = Input[m]; //X new input sample for
  57.  
  58. //LMS filter
  59.  
  60. else break;
  61. }
  62.  
  63. D = Desired[T]; //desired signal
  64.  
  65. Y = 0; //filter’output set to zero
  66.  
  67.  
  68. for (int i = 0; i < M; i++)
  69. Y += (W[i] * X[i]); //calculate filter output
  70.  
  71.  
  72. E = D - Y; //calculate error signal
  73.  
  74.  
  75. for (int i = 0; i < M; i++)
  76. W[i] = W[i] + (mu * E * X[i]); //update filter coefficients
  77.  
  78.  
  79. fprintf(Y_out, "\n % 10g % 10f", (float)T, Y);
  80. fprintf(error, "\n % 10g % 10f", (float)T, E);
  81. }
  82.  
  83. for (int i = 0; i < M; i++)
  84. fprintf(weights, "\n % 10d % 10f", i, W[i]);
  85.  
  86. fclose(Y_out);
  87. fclose(error);
  88. fclose(weights);
  89. }
Runtime error #stdin #stdout 0s 15248KB
stdin
Standard input is empty
stdout
Standard output is empty