Expansion of a function into a Matkad Fourier series. MathCAD series

Of course, the inability to work with trigonometric series is a rather serious minus, because Fourier trigonometric series are used for expansion periodic functions however, in fact, considering all the advantages of MthCD, this disadvantage is not so great. Fourier transforms The development of Fourier transforms played huge role in the emergence and development of a number of new areas of science and technology. Fourier series can also be considered as an approximation arbitrary functions certain restrictions in this are known by trigonometric series of infinite...


Share your work on social networks

If this work does not suit you, at the bottom of the page there is a list of similar works. You can also use the search button


Rows

Numerical and functional series play a very important role in mathematical analysis. They allow you to move from continuous presentation a function used, for example, in physics, to a discrete one, which is necessary to calculate its value using a computer. Therefore, working with series is supported by MathCAD "ohm to the fullest.


The most important operation, relating to both numerical and functional series this, of course, is the calculation of the sum of the series. You can easily find the operator for calculating this sum on the same Calculus panel, and it looks, like in mathematics, like a big greek letter sigma. To calculate the sum of a series, it is necessary to specify the summation index (for definiteness, we will assume that it is written by the letter n), the summation range and, of course, the value of the nth term of the series. In this case, you can use the infinity symbol to calculate the sums of infinite series (this symbol is located on the same Calculus panel, immediately after the calculation operator nth derivative). It is worth noting that calculating the sum of a finite series is possible both analytically and numerically, i.e. You can use both the equal sign and the arrow, but for an infinite series you can find the sum only analytically.

As in other areas where MathCAD uses its symbolic processor, the disadvantages of this very symbolic processor float to the surface and begin to irritate the user. The most important of them, which we have already encountered, is the reluctance to fully work with trigonometric functions. Therefore, if you need to calculate the sum of a trigonometric series, then MathCAD In this case, you can't count on it.

The sums of functional series can be immediately differentiated and integrated (about integrating functions using MathCAD "and we'll talk to you later), and it is possible to differentiate or integrate both the entire sum at once and individual members of the series. An example of how this can be done is shown in the illustration below. True, as you see, it may seem that The results may differ, but if you simplify the first expression, it becomes clear that in fact they are absolutely identical.

In general, MathCAD a really good assistant when working with derivatives, limits, series and, as we will see later, integrals. Of course, the inability to work with trigonometric series is a rather serious disadvantage, because trigonometric Fourier series are used to expand periodic functions, but in fact, taking into account all the advantages MathCAD "Oh, this minus is not so big. MathCAD we are quite capable of simplifying work with derivatives and integrals, and how to cope with the cumbersomeness of the results obtained using the environment itself MathCAD , we'll talk again.

Fourier transforms

The development of Fourier transforms played a huge role in the emergence and development of a number of new fields of science and technology. Suffice it to note that AC electrical engineering, electrical communications and radio communications are based on the spectral representation of signals. Fourier series can also be considered as the approximation of arbitrary functions (certain restrictions on this are known) by trigonometric series of infinite length. For a finite series length, the best root mean square approximations are obtained. MATLAB contains functions for performing fast one-dimensional and two-dimensional fast discrete Fourier transforms. For a one-dimensional array* with length N, direct and inverse Fourier transforms are implemented using the following formulas:

The direct Fourier transform transfers the description of a signal (a function of time) from the time domain to the frequency domain, and the inverse Fourier transform transfers the description of the signal from the frequency domain to the time domain. Numerous signal filtering methods are based on this.

15.4.1. Fourier transform

The mathematical meaning of the Fourier transform is to represent the signal y(x) in the form infinite sum sinusoids of the form F(v)sin(vx). The function F(v) is called the Fourier transform or Fourier integral, or the Fourier spectrum of the signal. Its argument v has the meaning of the frequency of the corresponding signal component. The inverse Fourier transform converts the spectrum F(V) into the original signal y(x). According to the definition,

As can be seen, the Fourier transform is an essentially complex quantity, even if the signal is real.

Fourier transform of real data

Fourier transform is of great importance for various mathematical applications and a very efficient algorithm called FFT (Fast Fourier Transform) has been developed for it. This algorithm is implemented in several built-in Mathcad functions that differ in normalization.

  • fft(y) direct Fourier transform vector;
  • FFT(Y) vector of direct Fourier transform in a different normalization;
  • ifft(v) inverse Fourier transform vector;
  • IFFT(V) vector of inverse Fourier transform in a different normalization;
    • y vector of real data taken at equal intervals of argument values;
    • v vector of real Fourier spectrum data taken at equal intervals of frequency values.

The argument of the direct Fourier transform, i.e. the vector y, must have exactly 2 n elements (n integer). The result is a vector with 1+2 n-1 elements. Conversely, the argument of the inverse Fourier transform must have 1+2 n-1 elements, and its result will be a vector of 2 n elements. If the number of data does not coincide with the power of 2, then it is necessary to pad the missing elements with zeros.

Rice. 15.24. Source data and inverse Fourier transform (Listing 15.20)

An example of calculating the Fourier spectrum for the sum of three sinusoidal signals of different amplitudes (shown as a solid curve in Fig. 15.24) is given in Listing 15.20. The calculation is carried out using N=128 points, and it is assumed that the data sampling interval хх is equal to A. In the penultimate line of the listing, the built-in function if ft is used, and in the last line the corresponding values ​​of the frequencies Qx are correctly determined. Please note that the calculation results are presented in the form of the module of the Fourier spectrum (Fig. 15.25), since the spectrum itself is complex. It is very useful to compare the resulting amplitudes and spectral peak locations with the definition of sinusoids in Listing 15.20.

Listing 15.20. Fast Fourier Transform

Rice. 15.25. Fourier transform (Listing 15.20)

The result of the inverse Fourier transform is shown as circles in the same figure. 15.24, the same as the original data. It can be seen that in the case under consideration, the signal y(x) is restored with great accuracy, which is typical for a smooth change in the signal.

Fourier transform of complex data

The fast Fourier transform algorithm for complex data is built into the corresponding functions, the name of which includes the letter “c”.

  • cfft(y) direct vector comprehensive transformation Fourier;
  • CFFT(y) vector of direct complex Fourier transform in a different normalization;
  • icfft(y) vector of the inverse complex Fourier transform;
  • ICFFT(V) vector of the inverse complex Fourier transform in a different normalization;
    • y vector of data taken at equal intervals of argument values;
    • v vector of Fourier spectrum data taken at equal intervals of frequency values.

The real Fourier transform functions take advantage of the fact that, in the case of real data, the spectrum is symmetric about zero, and output only half of it (see the "Fourier transform of real data" section above in this chapter). Therefore, in particular, from 128 real data, only 65 points of the Fourier spectrum were obtained. If we apply the complex Fourier transform function to the same data (Fig. 15.26), we obtain a vector of 128 elements. Comparing Fig. 15.25 and 15.26, it is possible to understand the correspondence between the results of the real and complex Fourier transform.

Rice. 15.26. Complex Fourier Transform (continued from Listing 15.20)

Two-dimensional Fourier transform

Mathcad has the ability to apply built-in functions of the complex Fourier transform not only to one-dimensional, but also to two-dimensional arrays, i.e., matrices. An example of this is shown in Listing 15.21 and Fig. 15.27 in the form of a graph of the level lines of the initial data and the calculated Fourier spectrum.

Listing 15.21. Two-dimensional Fourier transform

Rice. 15.27. Data (left) and its Fourier spectrum (right) (Listing 15.21)

Other similar works that may interest you.vshm>

13702. Bekanntschaft mit Mathematischen Programmen. Mathcad 16.5 KB
Die ufgbe: überprüfen die rbeit in Mthcd zeigen ds rbeitsdigrmm. uch soll mn die Funktion in symbol und betreibersform bekommen. Bild 1 ds rbeitsfenster in Mthcd Bild 2 ds Funktionsgrph Schlussfolgerung: mit Hilfe von Mthemtische Progrmm Mthcd wr die Funktion in symbol und betreibersform bekommen.
4286. Plotting graphs in Mathcad 29.41 KB
Let's consider the algorithm for constructing a graph on simple example. Let's enter the function by typing the expression: In the panel of mathematical symbols, click on the button with the image of a graph; a palette of graphs will appear on the screen. In the graph palette, click on the button with the image of a two-dimensional graph; a graph template will appear on the screen. Let's click outside the chart with the left mouse button.
13699. Connection of differential equation in MathCAD 134.69 KB
Unraveling the differential equation in MthCD Meta robots: with the help of the mathematical package MthCD, we can determine the structure of the differential equation in a different order of magnitude. Task: Results of the work: Everyday graphics in the middle of MthCD on baby 1 Little one 1 Summary: The mathematical package MthCD is very handy for solving mathematical tasks from every day on graphics.
2247. Dynamics series 46.97 KB
The dynamics series consists of two elements: the levels of the series characterizing the value of the characteristic being studied; periods of moments to which these levels relate. The initial one is a series of absolute values ​​where statistical indicators of the levels of the series are presented in absolute numbers with the corresponding units of measurement. In series of relative values, the levels of the series characterize changes in the relative indicators of the phenomena being studied over time and are usually expressed as percentages or coefficients. In the series of average values, the levels of the series...
8661. Number series 47.86 KB
Lecture No. 41 4 Lecture 41 TOPIC: Number series Plan. Alternating series. Properties of absolutely convergent series. If for two series with positive terms u1 u2 un 39.
8660. Functional series 60.71 KB
If you specify a specific numerical value of x, the series (40.1) will turn into a numerical series, and depending on the choice of the value of x, such a series can converge or diverge. Only convergent series are of practical value, so it is important to determine those values ​​of x at which the functional series becomes a convergent number series.
8658. Fourier series 62.27 KB
Lecture No. 44 6 Lecture 44 TOPIC: Fourier series Plan. Sufficient signs of decomposability in a Fourier series. Fourier series expansion of a non-periodic function. Fourier series for even and odd functions.
8659. Power series 41.1 KB
Lecture No. 43 3 Lecture 43 TOPIC: Power series Plan. Expansion of a function in power series. Taylor and Maclaurin series. Power series expansion of some elementary functions.
5992. Basics of working with MathCAD. Mathematical expressions. Data Types 494.07 KB
Functions of MthCD is a powerful and at the same time simple universal environment for solving problems in various branches of science and technology finance and economics physics and astronomy mathematics and statistics MthCD remains the only system in which a description of the solution mathematical problems is specified using familiar mathematical formulas and symbols. MthCD allows you to perform both numerical and analytical symbolic calculations, has an extremely convenient mathematics-oriented interface and excellent scientific graphics tools. MthCD system...
4446. Variation series and their numerical characteristics 67.52 KB
Mathematical statistics– a science that makes it possible to extend conclusions drawn from the study of a part of a population (random sample) to the entire population (general population). It is also defined as the science of decision making under conditions of uncertainty.

Mod(x, y) – remainder of x divided by y. The result has the same sign as x; angle(x, y) – angle (in radians) between the positive x-axis and the vector (x, y) in the XY plane. Arguments must be real. Returns a value between 0 and 2π. ceil(3.25) = 4 floor(3.25) = 3 mantissa (x) := x − floor(x) mantissa (3.45) = 0.45 Traditional rounding: roundoff (x) := if(mantissa (x)< 0.5, floor(x) , ceil(x)) roundoff (3.46) = 3 roundoff (3.56) = 4 Рис. 14. Создание функций округления На рис. 14 показано, как из этих функций могут быть сформированы функции округления. 4.4. Дискретное преобразование Фурье В Mathcad входят два типа функций для дискретного прямого и об- ратного преобразования Фурье: fft/ifft и cfft/icfft. Эти функции дискрет- ны: они берут в качестве аргументов и возвращают векторы и матрицы. Они не могут быть использованы с другими функциями. Используйте функции fft и ifft, если выполнены два следующих ус- ловия: аргументы вещественны, и вектор данных имеет 2m элементов. Первое условие необходимо, потому что функции fft/ifft используют тот факт, что для вещественных данных вторая половина преобразова- ния Фурье является комплексно сопряженной с первой. Mathcad отбра- сывает вторую половину вектора-результата. Это сохраняет время и память при вычислениях. Пара функций cfft/icfft не использует симметрию в преобразова- нии. По этой причине необходимо использовать их для комплексных данных. 41 Второе условие требуется, потому что пара функций fft/ifft исполь- зует высоко эффективный алгоритм быстрого преобразования Фурье. Для этого вектор аргумента, используемого с fft, должен иметь 2m эле- ментов. В функциях cfft/icfft использован алгоритм, который допускает в качестве аргументов как матрицы, так и векторы произвольного раз- мера. Когда эта пара функций используется с матрицей в качестве аргу- мента, вычисляется двумерное преобразование Фурье. Следует иметь в виду, что если для прямого преобразования исполь- зована функция fft, то для обратного преобразования необходимо ис- пользовать функцию ifft. Аналогично используются функции cfft/icfft. 4.5. Преобразование Фурье в вещественной области Для вещественных векторов с 2m элементами предпочтительно ис- пользовать функции fft/ifft. Функция fft(v) возвращает дискретное пре- образование Фурье, векторный аргумент которой можно интерпретиро- вать как результат измерений через равные промежутки времени некоторого сигнала. Вектор v должен содержать 2m элементов. Резуль- тат – комплекснозначный вектор размерности 1 + 2m–1. Если v имеет размерность, отличную от 2m, Mathcad выдает сообщение об ошибке "неверный размер вектора". Элементы вектора, возвращаемого fft, вычисляются по формуле n −1 ∑ vk e 2 πi (j n) k . 1 Cj = n k =0 В этой формуле n – число элементов в v, i – мнимая единица. Эле- менты в векторе, возвращенном функцией fft, соответствуют различ- ным частотам. Чтобы восстановить фактическую частоту, необходимо знать частоту измерения исходного сигнала. Если v есть n-мерный век- тор, переданный функции fft, и частота измерения исходного сигнала – fs, то частота, соответствующая Ck k fk = fs. n Обратите внимание, что это делает невозможным обнаружить часто- ты выше частоты измерения исходного сигнала. Это ограничение, нала- гаемое не Mathcad, а самой сутью проблемы. Чтобы правильно восста- новить сигнал по его преобразованию Фурье, необходимо произвести 42 i:= 0 .. 63 xi:= sin  π⋅  + rnd (1) − 0.5 i Формирование сигнала:    10  Применяется комплексное преобразование Фурье: c:= fft(x) N:= last (c) N = 32 Обращение преобразования Фурье: z:= ifft(c) N2:= last (z) N2 = 63 j:= 0 .. N k:= 0 .. N2 Графическое представление сигнала zk = xj = 2 –0.499 –0.499 2.34·10 –3 2.34·10–3 0.673 0.673 xi 0 0.659 0.659 1.274 1.274 0.674 0.674 –2 0 20 40 60 80 1.162 1.162 i 0.613 0.613 Фурье-образ 0.179 0.179 4 –0.044 –0.044 0.489 0.489 –0.69 –0.69 cj 2 –1.079 –1.079 –0.777 –0.777 –0.849 –0.849 –1.334 –1.334 0 0 10 20 30 40 j Рис. 15. Быстрые пр6еобразования Фурье в Mathcad 43 измерения исходного сигнала с частотой, по крайней мере, вдвое боль- шей, чем ширина полосы частот. Подробное обсуждение этой пробле- мы содержится в специальных курсах. Функция ifft(v) возвращает обратное дискретное преобразование Фурье. Вектор v должен иметь 1 + 2m элементов, где m – целое. Резуль- тат есть вектор размерности 2m+1. Аргумент v – вектор, подобный созданному функцией fft. Чтобы вы- числить результат, Mathcad сначала создает новый вектор w, комплекс- но сопряженный v, и присоединяет его к вектору v. Затем Mathcad вы- числяет вектор d, элементы которого вычисляются по формуле n −1 ∑ wk e−2πi(j n)k . 1 dj = n k =0 Это та же самая формула, что и для fft, кроме знака минус в функции экспоненты. Функции fft и ifft – точные обращения. Для всех веще- ственных v справедливо ifft(fft(v)) = v. Пример использования прямого и обратного преобразований Фурье приведен на рис. 15. 4.6. Alternative forms Fourier transforms The definitions of the Fourier transform discussed above are not the only possible ones. For example, the following definitions of direct and inverse Fourier transforms are often used: n n ∑ f (τ)e−2πi(ν n)τ ; f (τ) = ∑ F (ν) e () . 1 2 πi τ / n ν F (ν) = n τ=1 v =1 These definitions are implemented in the built-in functions FFT/IFFT and ICFFT. They differ from the fast Fourier transform in the following way: instead of the coefficient 1 n, both formulas are preceded by the coefficient 1/n and the coefficient 1 in the inverse transform; The minus sign appears in the exponent of the direct transformation and disappears in the inverse formula. 4.7. Piecewise continuous functions Piecewise continuous functions are useful for controlling branches and stops computing processes. There are five functions 44 Using conditional statements 2 x:= −2 , − 1.8 .. 2 f (x) := x − 1 g (x) := if(f (x) > 0 , f (x) , 0) g(x) is equal to f(x) when f(x) > 0, otherwise 0 4 4 2 f (x) g(x) 2 0 2 0 2 0 2 2 0 2 x x h (x) := if(x ≥ 1 , f (x) , − f (x)) otherwise –f(x) 5 h(x) 0 Continue calculations until condition is met 5 2 0 2 2 quess − a< err x −2 N:= 100 i:= 0 .. N a:= 1000 quess 0:= 10 err:= 10  quess i + a   quess i  quess i+ 1:= until (quess i) − a − err ,  2  2  N2:= last (quess) − 1 j:= 0 .. N2 j= quess j = (quess j)2 = 0 10 100 Число итераций N2 = 5 1 55 3.025·10 3 answer:= quess N2 2 36.591 1.339·10 3 3 31.96 1.021·10 3 answer = 31.623 4 31.625 1·10 3 5 31.623 1·10 3 Рис. 16. Условные выражения в Mathcad 45 Mathcad, относящихся к этому классу. Функция if полезна для выбора одного из двух значений, определяемого условием. Ступенчатая функ- ция Хевисайда Ф(х) и символ Кронекера δ(m, n) во многом аналогичны функции if. Функция until используется, чтобы управлять процессом итераций. Функция if(cond, tval, fval) возвращает значение tval, если cond отли- чен от 0 (истина) и возвращает fval, если cond равен 0 (ложь). Обычно в качестве аргумента cond выбирается булево выражение вида w = z, x >y, x< y, x ≥ y, x ≤ y, w ≠ z. Можно объединять булевы операторы, чтобы записать более сложные условия. Например, условие (x < 1) ⋅ (x >0) acts like logical "and", which returns 1 only if x is between 0 and 1. Similarly, the expression (x > 1) + (x< 0) действует подобно логическому "или", возвращающему 1, если x >1, or x< 0, и 0, если x заключено между 0 и 1. Функция until (x, z) возвращает z, пока выражение x не становится отрицательным; должно содержать дискретный аргумент. Функция until позволяет останавливать вычисления для последовательных значений дискретного аргумента. Функция until полезна в итеративных процес- сах с определенным условием сходимости. На рис. 16 приведены примеры использования функций if и until. Функция Хевисайда эквивалентна следующей функции: Ф (x) := if (x < 0,0,1) Символ Кронекера δ(m, n) возвращает 1, если m = n; иначе 0. Оба аргумента должны быть целочисленными. Символ Кронекера эквива- лентен функции δ (m, n) := if (m = n,1,0) Ступенчатая функция Хевисайда может быть использована для со- здания импульса шириной w: pulse (x, w) := Ф (x) − Ф (x − w) Можно определить также две полезные функции lowpass и highpass. Они обе являются фильтрами – умножение на них какого-либо сигнала 46 вырезает из этого сигнала кусок вокруг точки x, имеющий ширину 2w. Разница состоит в том, что lowpass оставляет только вырезанный ку- сок, highpass – все, кроме вырезанного куска. lowpass (x, w) := pulse (x+w, 2 ⋅ w) highpass (x, w) := 1 − pulse (x+w, 2 ⋅ w) 4.8. Статистические функции Для вычисления статистических оценок случайных совокупностей чисел в Mathcad могут использоваться следующие функции: mean(A) – возвращает среднее значение элементов массива А раз- мерности m × n по формуле m −1 n −1 ∑ ∑ Aij ; 1 mean(A) = mn i =0 j =0 var(A) – возвращает дисперсию элементов массива А размерности m × n согласно формуле m −1 n −1 ∑ ∑ Aij − mean(A) 1 2 var(A) = ; mn i =0 j =0 stdev(A) - возвращает среднеквадратичное отклонение (квадратный корень из дисперсии) элементов m × n массива А stdev(A) = var(A). 4.9. Плотности распределения вероятности Эти функции показывают отношение вероятности того, что случай- ная величина попадает в малый диапазон значений с центром в задан- ной точке, к величине этого диапазона. В Mathcad имеются функции семнадцати плотностей вероятностей. Отметим только некоторые из них: dnorm(x, µ, σ) – возвращает плотность вероятности нормального рас- пределения 1  (x − µ) 2  dnorm(x, µ, σ) = exp  − , 2πσ  2σ 2  47 в котором µ и σ есть среднее значение и среднеквадратичное отклоне- ние, σ >0; dunif(x, a, b) – calculates the probability density of a uniform distribution  1 , x ∈ ,  dunif(x, a, b) =  b − a  0,  x ∉ in which a and b are boundary points interval, a< b. 4.10. Функции распределения Эти функции возвращают вероятность того, что случайная величи- на меньше или равна определенному значению. Функция распределе- ния вероятности – это функция плотности вероятности, проинтегриро- ванная от минус бесконечности до определенного значения. Приведем две из них: pnorm(x, µ, σ) – возвращает функцию нормального распределения со средним µ и среднеквадратическим отклонением σ (σ >0); punif(x, a, b) – returns the uniform distribution function. a and b are the boundary values ​​of the interval (a< b). Mathcad имеет ряд функций для генерирования случайных чисел, имеющих разнообразные распределения вероятностей. Приведем две из них: rnorm(m, µ, σ) – возвращает вектор m случайных чисел, имеющих нормальное распределение (σ >0); runif(m, a, b) – returns a vector of m random numbers having a uniform distribution, in which a and b are the boundary points of the interval (a< b). Остальные встроенные статистические функции и их описания мож- но посмотреть, выбрав команду Функция из меню Вставка. 4.11. Интерполяция и функции предсказания Интерполяция заключается в использовании значений некоторой функции, заданных в ряде точек, чтобы предсказать значения между ними. В Mathcad можно или соединять точки данных прямыми линия- ми (линейная интерполяция) или соединять их отрезками кубического полинома (кубическая сплайн-интерполяция). 48 В отличие от функций регрессии, обсуждаемых в следующем разде- ле, функции интерполяции определяют кривую, точно проходящую че- рез заданные точки. Из-за этого результат очень чувствителен к ошиб- кам данных. Если данные зашумлены, следует рассмотреть возможность использования регрессии вместо интерполяции. Для линейной интерполяции используется функция linterp(vx, vy, x), которая по векторным данным vx и vy возвращает линейно интерполи- руемое значение y, соответствующее третьему аргументу x. Аргументы vx и vy должны быть векторами одинаковой длины. Вектор vx должен содержать вещественные значения, расположенные в порядке возраста- ния. Эта функция соединяет точки данных отрезками прямых, созда- вая, таким образом, broken line. The interpolated value for a particular x is the y-ordinate of the corresponding point on the polyline. An example of linear interpolation is shown in Fig. 17. Cubic spline interpolation allows you to fit a curve through a set of points such that the first and second derivatives of the curve are continuous at each point. This curve is formed by creating a series of cubic polynomials passing through sets of three adjacent points. Cubic polynomials are added to each other to form one curve. To fit a cubic spline through a set of points: Create vectors vx and vy containing the x and y coordinates through which to fit the cubic spline. The vx elements must be arranged in ascending order; calculate the vector vs:=cspline(vx, vy). The vector vs contains the second derivatives of the interpolation curve at the points under consideration. To find the interpolated value at an arbitrary point, say x0, calculate interp(vs, vx, vy, x0), where vs, vx and vy are the vectors described earlier. Note that you can do the same thing by computing interp(cspline(vx, vy),vx,vy, x0). An example of using cubic spline interpolation is shown in Fig. 17 below. 49 Linear interpolation i:= 0 .. 5 VXi:=i VYi:=vd(1) VXi = VYi = –3 linterp(VX, VY, 1.5) = 0.389 0 1.268 10 1 0.193 linterp(VX, VY, 3.75 ) = 0.705 2 0.585 linterp(VX, VY, 4.1) = 0.758 3 0.35 4 0.823 x:= 0 , 0.1.. 5 5 0.174 1 linterp(VX , VY , x) 0.5 VYi 0 0 2 4 6 x , VX i Cubic spline interpolation i:= 0 .. 5 VXi:= i VYi:= rnd (1) VS:= lspline (VX, VY) interp (VS, VX, VY, 1.5) = 0.188 interp (VS, VX, VY , 3.75) = 0.868 interp (VS, VX, VY, 4.1) = 0.989 1 VYi = 0.71 interp(VS, VX, VY, x) 0.304 0.5 VYi 0.091 0.147 0.989 0 0 2 4 6 0.119 x , VX i Fig. 17. Examples of interpolation 50

Trigonometric Fourier series using Mathcad.

Purpose of the work

Learn to expand periodic functions into trigonometric Fourier series using Mathcad and build graphs of partial sums of Fourier series.

Equipment

MathCAD software package.

Work progress

Option

1) Expand the function into a trigonometric Fourier series

2) Expand the function into a trigonometric Fourier series in cosines

3) Expand the function into a trigonometric Fourier series in terms of sines

Permission to work

3.2.1 The trigonometric Fourier series of a function is a functional series of the form

3.2.4 Fourier coefficients were calculated for the function f(x) (when expanded in cosines)

a 1 = 5, a 2 = 6, a 3 = 7

Write the trigonometric Fourier series

3.2.5 The function f(x) is expanded into a Fourier series in terms of sines (odd), then

Sheet
Document No. No.
Signature
Sheet
Document no.
Signature
Date
Sheet

3.1.2. Find the numerical characteristics of the random variable x (x is the winnings of the owner of one lottery ticket).

The lottery gives away ____ tickets.

Of these, they win ____ rubles

Of these, they win ____ rubles each.

3.1.3. Find the numerical characteristics of the random variable “x”

A). 0.15 b) -0.35 c) 0.35 d) 0.25 e) cannot be determined.

3.2.3 There are 200 tickets in the lottery. There are 30 winning tickets. What is the probability that the ticket is not a winning one?

A). 1.7 b) 0.7 c) 0.17 d) 0.85 d) 0.15

3.2.4 Write down a formula for calculating the variance of a discrete random variable.

3.2.5 Write a formula for calculating the standard deviation of a discrete random variable.

________________________________________________________________________________

3.2.6. D (y) = 25. What is the standard deviation?

A). ± 5 b) 5 c) -5 d) cannot be determined.

3.2.7 How can you solve an equation in MathCAD

______________________________________________________________________________

______________ is allowed to work

Work results

4.1. M(x) = ____________ D(x) = ____________ σ (x) = ___________

Sheet
Document no.
Signature
Date
Sheet
PR.140448.00.00
PRACTICAL WORK 12

Finding point and interval estimates

unknown distribution parameters in Excel

1. Purpose of the work

Using a given sample, learn to determine the numerical characteristics of the sample and estimate unknown parameters of the general population, estimate from a given confidence probability mathematical expectation of the population.

2.Equipment:

IBM PC, Microsoft Excel shell.

Work progress

3. 1 Option

Estimate with a given confidence probability γ = mathematical expectation of the general population for a given sample

_____________________________________________________________________________________

3. 2 Permission to work

1. How is the sample mean calculated?

2. How is sample variance calculated?

____________________________________________________________________________________________________________________________________________________________

3. How is standard deviation calculated?

____________________________________________________________________________________________________________________________________________________________

4. How is corrected sample variance calculated?

____________________________________________________________________________________________________________________________________________________________

5. Than point estimate unknown distribution parameter differs from interval?

____________________________________________________________________________________________________________________________________________________________

6. How is the interval calculated to estimate the mathematical expectation of the population?

________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________


7. What is the Student coefficient denoted?

Change
Sheet
Document no.
Signature
Date
Sheet
PR.140448.00.00
____________________________________________________________________________________________________________________________________________________________

8. What does the value of the Student coefficient depend on?

____________________________________________________________________________________________________________________________________________________________

The following are allowed to work:_______________________________________________

Work results

σ in = S in = t γ =

Conclusion

In the course of this work, I applied the formulas for point and interval estimates____________________________________________________________

_________________________________________________________________



Change
Sheet
Document no.
Signature
Date
Sheet
PR.140448.00.00

The mathematical meaning of the Fourier transform is to represent the signal y(x) as an infinite sum of sinusoids of the form F(v)sin(vx). The function F(v) is called the Fourier transform or Fourier integral, or the Fourier spectrum of the signal. Its argument v has the meaning of the frequency of the corresponding signal component. The inverse Fourier transform converts the spectrum F(V) into the original signal y(x). According to the definition,

As can be seen, the Fourier transform is an essentially complex quantity, even if the signal is real.

Fourier transform of real data

Fourier transform is of great importance for various mathematical applications and a very efficient algorithm called FFT (Fast Fourier Transform) has been developed for it. This algorithm is implemented in several built-in Mathcad functions that differ in normalization.

  • fft(y) - direct Fourier transform vector;
  • FFT(Y) is the vector of direct Fourier transform in a different normalization;
  • ifft(v) - inverse Fourier transform vector;
  • IFFT(V) is the vector of the inverse Fourier transform in a different normalization;
    • y is a vector of real data taken at equal intervals of argument values;
    • v is a vector of real Fourier spectrum data taken at equal intervals of frequency values.

The argument of the direct Fourier transform, i.e., the vector y, must have exactly 2 n elements (n is an integer). The result is a vector with 1+2 n-1 elements. Conversely, the argument of the inverse Fourier transform must have 1+2 n-1 elements, and its result will be a vector of 2 n elements. If the number of data does not coincide with the power of 2, then it is necessary to pad the missing elements with zeros.

Rice. 15.24. Source data and inverse Fourier transform (Listing 15.20)

An example of calculating the Fourier spectrum for the sum of three sinusoidal signals of different amplitudes (shown as a solid curve in Fig. 15.24) is given in Listing 15.20. The calculation is carried out using N=128 points, and it is assumed that the data sampling interval хх is equal to A. In the penultimate line of the listing, the built-in function if ft is used, and in the last line the corresponding values ​​of the frequencies Qx are correctly determined. Please note that the calculation results are presented in the form of the module of the Fourier spectrum (Fig. 15.25), since the spectrum itself is complex. It is very useful to compare the obtained amplitudes and the location of the spectrum peaks with the definition of sinusoids in Listing 15.20.

Listing 15.20. Fast Fourier Transform

Rice. 15.25. Fourier transform (Listing 15.20)

The result of the inverse Fourier transform is shown as circles in the same figure. 15.24, the same as the original data. It can be seen that in the case under consideration, the signal y(x) is restored with great accuracy, which is typical for a smooth change in the signal.

Fourier transform of complex data

The fast Fourier transform algorithm for complex data is built into the corresponding functions, the name of which includes the letter “c”.

  • cfft(y) - vector of direct complex Fourier transform;
  • CFFT(y) is the vector of the direct complex Fourier transform in a different normalization;
  • icfft(y) is the vector of the inverse complex Fourier transform;
  • ICFFT(V) is the vector of the inverse complex Fourier transform in a different normalization;
    • y is a vector of data taken at equal intervals of argument values;
    • v is a vector of Fourier spectrum data taken at equal intervals of frequency values.

The real Fourier transform functions take advantage of the fact that, in the case of real data, the spectrum is symmetric about zero, and output only half of it (see the "Fourier transform of real data" section above in this chapter). Therefore, in particular, using 128 real data, only 65 points of the Fourier spectrum were obtained. If we apply the complex Fourier transform function to the same data (Fig. 15.26), we obtain a vector of 128 elements. Comparing Fig. 15.25 and 15.26, it is possible to understand the correspondence between the results of the real and complex Fourier transform.

Rice. 15.26. Complex Fourier Transform (continued from Listing 15.20)

Two-dimensional Fourier transform

Mathcad has the ability to apply built-in functions of the complex Fourier transform not only to one-dimensional, but also to two-dimensional arrays, i.e., matrices. An example of this is shown in Listing 15.21 and Fig. 15.27 in the form of a graph of the level lines of the initial data and the calculated Fourier spectrum.

Listing 15.21. Two-dimensional Fourier transform

Rice. 15.27. Data (left) and its Fourier spectrum (right) (Listing 15.21)

Because the result interpolation formulas Newton and Lagrange are the same polynomial of the Nth order, then their error behaves the same way.

Example 3.4. For the initial data used in example 3.1, we calculate the value of Newton's polynomial. First, fill out the divided difference table:

F(xi ,xj)

F(xi ,xj ,xk )

F(x0 ,x1 ,x2 ,x3 )

z–xi

Using Newton's formula, we get:

P 3 (1)= –1+0.6 1+(–0.1) 1 (–1)+0.0857 1 (–1) (–2)= –0.129.

3.6 Fourier series

The Fourier series allows us to study both periodic and non-periodic functions by decomposing them into components. Alternating currents and stress, displacement, speed and acceleration of crank mechanisms, acoustic waves - these are typical practical examples of the use of periodic functions in engineering calculations. In signal processing terms, the Fourier transform takes the time series representation of a signal function and maps it to a frequency spectrum. That is, it turns a function of time into a function of frequency; This is the decomposition of a function into harmonic components at different frequencies. The Fourier transform can represent a time-varying signal as a function of frequency and amplitude, and it also provides information about phase (Fig. 3.4).

Fourier series expansion is based on the assumption that all having practical significance functions in the interval π ≤x≤ π can be expressed as convergent trigonometric series (a series is considered convergent if the sequence of partial sums composed of its terms converges).

According to the Fourier hypothesis, there is no function that cannot be expanded into a trigonometric series. Let us expand the function f (t) into a series on the interval [–π, π]

f (t) = a 0 /2 + a 1 cos(t) + a 2 cos(2t) + a 3 cos(3t) + … + b 1 sin(t) + b 2 sin(2t) + b 3 sin (3t )+…,

where the nth elements of the series are expressed as

f (t) cos(nt)dt ,

Rice. 3.4. Illustration for Fourier series expansion

The coefficients a n and b n are called Fourier coefficients, and the representation of the function f (t) according to formula (3.1) is Fourier series expansion. Sometimes a Fourier series expansion presented in this form is called a real Fourier series expansion, and the coefficients are called real Fourier coefficients (as opposed to a complex expansion).

Let us analyze expressions (3.2) and (3.3). Coefficient a 0 represents the average value of the function f (t) on the segment [–π, π] or the constant component of the signal f (t). Coefficients a n and b n (for n > 0) are the amplitudes of the cosine and sine components of the function (signal) f (t) with an angular frequency equal to n. In other words, these coefficients specify the magnitude of the frequency components of the signals. For example, when we talk about a sound signal with low frequencies (for example, the sounds of a bass guitar), this means that the coefficients a n and b n are greater for smaller values ​​of n and vice versa - in high-frequency sound

vibrations (for example, the sound of a violin) are greater when large values n.

The oscillation of the longest period (or lowest frequency), represented by the sum of a 1 cos(t) and b 1 sin(t) is called the oscillation of the fundamental frequency or the first harmonic. An oscillation with a period equal to half the period of the fundamental frequency is the second harmonic, an oscillation with a period equal to 1/n of the fundamental frequency is the n-harmonic. Thus, by expanding the function f (t) into a Fourier series, we can make the transition from the time domain to the frequency domain. Such a transition is usually necessary to identify signal features that are “invisible” in the time domain.

Please note that formulas (3.2) and (3.3) are applicable for a periodic signal with a period equal to 2π. In the general case, a periodic signal with period T can be expanded into a Fourier series, then the segment [–T /2, T /2] is used in the expansion. The period of the first harmonic is equal to T and the components take the form cos(2πt /T) and sin(2πt /T), the components of the n-harmonic are cos(2πtn /T) and sin(2πtn /T). If we denote the angular frequency of the first harmonic ω0 = 2π/T, then the components of the n-harmonics take the form cos(ω0 nt), sin(ω0 nt) and

cos(nt) b sin(nt) ,

f(t)

where the Fourier coefficients are calculated using the formulas

T/2

(t ) cos(0 nt )dt ,

T/2

f (t ) sin(0 nt )dt .

T/2

T/2

Fourier series expansion is used for harmonic or spectral analysis periodic signals. For spectral analysis of non-periodic signals it is used Fourier transform. To do this, we represent series (3.4) using a system of basis functions in the form of exponentials with imaginary exponents:

2 jnt

f(t)

C n exp(

T/2

2 jnt

f(t)exp(

T/2

Omitting a number of calculations, we write expression (3.6) in the form

C () f (t ) exp(j t )dt .

This formula is called direct Fourier transform or Fourier transform. Typically, the Fourier transform is denoted by the same (only uppercase) letter as the function being approximated (which is usually denoted by a lowercase letter -

F () f (t ) exp(j t )dt .

The function F (ω) is called the function spectral density(or simply spectral density, Fourier transform, Fourier image). The range of values ​​of the function F (ω) in the general case is the set of complex numbers.

Inverse Fourier Transform , providing restoration

The change in the original function f (t) from the spectral density function is calculated as follows

f (t ) F () exp(j t )dt .

Discrete Fourier transform (DFT, DFT - Discrete Fourier Transform) is one of the Fourier transforms widely used in digital signal processing algorithms (its modifications are used in audio compression in MP3, compression images in JPEG, etc.), as well as in other areas related to the analysis of frequencies in a discrete (for example, digitized analog) signal. The discrete Fourier transform requires as input discrete function. Such functions are often created by sampling (sampling values ​​from continuous functions). The disadvantage of this algorithm is the large amount of repetitive calculations. Eliminating these redundant operations results in the so-called algorithm

fast Fourier transform, which is usually used.

Fast Fourier Transform (FFT, FFT) - an algorithm for fast calculation of the discrete Fourier transform (DFT). That is, the calculation algorithm takes a number of actions less than O(N 2 ), required for direct (by formula) calculation of the DFT (N is the number of signal values ​​measured over a period, as well as the number of decomposition components). Sometimes FFT means one from fast algorithms, called the frequency/time decimation algorithm or the radix 2 algorithm.

In order to implement the Fourier transform in the MathCAD package, you need to select the fourier operator in the Symbolic panel for the direct transformation and invfourier for the reverse one. This operator must be placed next to the function that needs to be converted, and the only parameter must be the variable relative to which this function will be converted. Examples of using display-

us pic. 3.5 for the function f (t) e 2 t and in Fig. 3.6, where amplitude-frequency modulation is applied to the function f (t), and then the result is expanded into a series.

Rice. 3.5. Example of Fourier series expansion using the symbolic function fourier

Rice. 3.6. Example of Fourier series expansion using the symbolic function fourier

MathCAD contains functions for fast discrete Fourier transform (FFT) and its inversion. There are two types of functions for the discrete Fourier transform: fft and ifft, cfft and icfft. These functions are discrete: they take vectors and matrices as arguments and return them.

The fft and ifft functions are used if the following conditions are met: (1) the arguments are real; (2) – the data vector has 2m elements.

In all other cases, the cfft and icfft functions are used.

The first condition must be met because the fft and ifft functions use the fact that for real data the second half of the Fourier transform is complex conjugate to the first. MathCAD discards the second half of the result vector, which saves time and memory during calculations. The pair of functions cfft and icfft do not use symmetry in the conversion and can be used for real and complex numbers.

The second condition is required because the function pair fft and ifft use a highly efficient fast Fourier transform algorithm. For this argument vector, use-

given by the function fft , must consist of 2m elements. The algorithm for the cfft and icfft functions accepts vectors and matrices of arbitrary size as arguments. For the 2D Fourier transform, only these functions are used. The functions fft and ifft, cfft and icfft are mutually inverse to each other, that is, true:

and icfft(cfft(v)) v .

In Fig. Figure 3.7 illustrates the use of the functions ff t(v) and ifft(v) for a sine wave signal that is interfered with using the rnd(x) function, which generates random numbers in the range from 0 to x.

Rice. 3.7. Forward and inverse Fourier transform using fft and ifft functions

These graphs show the Fourier image of signal c and a comparison of the original signal x with the one reconstructed from the Fourier image. More details about Fourier analysis can be read in and.

3.7 Method least squares

In all of the above methods of approximating a function, the interpolation conditions were met exactly. However, in cases where the initial data x i, f i, i= 1,...,N, are given with some error, only an approximate execution can be required.

Definition of interpolation conditions: |F(x i ) – f i |< . Это условие означает, что интерполирующая функция F(x) проходит не точно через заданные точки, а в некоторой их окрестности, так, например, как это показано на рис. 3.8. Приблизим исходные данные глобальным полиномом. Если решать задачу интерполяции точно, то полином должен иметь степень N . При рассмотрении полинома Лагранжа мы выяснили, что полином N –й степени хорошо приближает исходную функцию только при небольших значениях N .

Rice. 3.8. Approximate fulfillment of interpolation conditions

We will look for a low degree polynomial, for example, P 3 (x)=a 1 +a 2 x+a 3 x 2 +a 4 x 3. If N >4, then the exact problem has no solutions: for four unknown coefficients (a 1 , a 2 , a 3 , a 4 ), the interpolation conditions give N > 4 equations. But now exact fulfillment of the interpolation conditions is not required; we want the polynomial to pass near the given points. There are many such polynomials, each of which is defined by its own set of coefficients. Among all possible polynomials of this type, we choose the one that has the smallest standard deviation at the interpolation nodes from the given values, i.e. the polynomial must be closest to given points of all possible polynomials of the third degree in the sense least squares method(MNC). At the i-th point

the line P 3 (x) deviates from the value f i by the amount (P 3 (x i) – f i). We sum up the squared deviations of the polynomial over all points i= 1, 2,…, N, and obtain the functional of the squared deviations:

G(a1 ,a2 ,a3 ,a4 ) (P3 (xi ) fi )2

a2 xi a3 xi 2 a4 xi 3 fi )2 .

Let's find the minimum of this functionality. To do this, we equate to zero its partial derivatives with respect to the variables a 1, a 2, a 3, a 4. Using standard differentiation rules, we get:

2 (a 1

a2 xi a3 xi 2 a4 xi 3 fi ) 0

a3 xi 2 a4 xi 3 fi ) 0

G 2 xi (a1 a2 xi

2 x i 2 (a 1

a2 xi

a3 xi 2 a4 xi 3 fi ) 0

2 x i 3 (a 1

a2 xi

a3 xi 2 a4 xi 3 fi ) 0

Collecting the coefficients for the unknowns a i, we obtain a SLAE with respect to the vector of unknowns (a 1, a 2, a 3, a 4):

N a1 xi a2 xi 2

a3 xi 3 a4 fi

xi 2 a2

xi 3 a3

xi 4

f i x i

xi 2 a1

xi 3 a2

xi 4 a3

xi 5

f i x i2

xi 3 a1

xi 4 a2

xi 5 a3

xi 6

f i x i3

The resulting system is called normal. To solve it, standard methods for solving SLAEs are used. As a rule, the number of unknowns of the system (i.e., the number of coefficients of the interpolating function) is small, so you can use exact methods for solving SLAEs, for example, the Cramer method or the Gauss method. The least squares method allows you to “approximate” the original data using a linear combination of any elementary functions. The approximations of linear F (x )=a 1 +a 2 x, , trigonometric F (x )=a 1 sin(x )+a 2 cos(x), exponential F (x )=a 1 e x are often used

N a1 xi a2

xi a1 xi 2 a2 fi xi

We calculate

xi 2,

f i x i,

substitute it into normal

Rice. 3.9. Selection of linear

5a 1.4a

MNC dependencies

0.148. The graph of the function F (x)=-0.04+0.57x is shown in Fig. 3.9 with a solid line. The dots show the original data. You can see that the found linear function really brings the given points closer.

In MathCAD, the least squares method is closely related to linear regression (y(x) = b + ax), since the coefficients a and b are calculated from the condition of minimizing the sum of squared errors |b + ax i – y i |. For calculations in MathCAD there are two overlapping methods:

line (x,y) returns a vector of two coefficient elements linear regression b + ax ;