c3-5 (779475)

Файл №779475 c3-5 (Numerical Recipes in C)c3-5 (779475)2017-12-27СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла

120Chapter 3.Interpolation and Extrapolation3.5 Coefficients of the Interpolating Polynomialy = c 0 + c1 x + c2 x 2 + · · · + cN x N(3.5.1)then the ci ’s are required to satisfy the linear equation1x01...1x20x1...x21...xNx2N c· · · xN00· · · xN1   c1·..   ....· · · xNcNNy0   y1= .  ..yN(3.5.2)This is a Vandermonde matrix, as described in §2.8. One could in principle solveequation (3.5.2) by standard techniques for linear equations generally (§2.3); howeverthe special method that was derived in §2.8 is more efficient by a large factor, oforder N , so it is much better.Remember that Vandermonde systems can be quite ill-conditioned.

In such acase, no numerical method is going to give a very accurate answer. Such cases donot, please note, imply any difficulty in finding interpolated values by the methodsof §3.1, but only difficulty in finding coefficients.Like the routine in §2.8, the following is due to G.B.

Rybicki. Note that thearrays are all assumed to be zero-offset.Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use. Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).Occasionally you may wish to know not the value of the interpolating polynomialthat passes through a (small!) number of points, but the coefficients of that polynomial.

A valid use of the coefficients might be, for example, to computesimultaneous interpolated values of the function and of several of its derivatives (see§5.3), or to convolve a segment of the tabulated function with some other function,where the moments of that other function (i.e., its convolution with powers of x)are known analytically.However, please be certain that the coefficients are what you need. Generally thecoefficients of the interpolating polynomial can be determined much less accuratelythan its value at a desired abscissa.

Therefore it is not a good idea to determine thecoefficients only for use in calculating interpolating values. Values thus calculatedwill not pass exactly through the tabulated points, for example, while valuescomputed by the routines in §3.1–§3.3 will pass exactly through such points.Also, you should not mistake the interpolating polynomial (and its coefficients)for its cousin, the best fit polynomial through a data set. Fitting is a smoothingprocess, since the number of fitted coefficients is typically much less than thenumber of data points.

Therefore, fitted coefficients can be accurately and stablydetermined even in the presence of statistical errors in the tabulated values. (See§14.8.) Interpolation, where the number of coefficients and number of tabulatedpoints are equal, takes the tabulated values as perfect.

If they in fact contain statisticalerrors, these can be magnified into oscillations of the interpolating polynomial inbetween the tabulated points.As before, we take the tabulated points to be yi ≡ y(xi ). If the interpolatingpolynomial is written as3.5 Coefficients of the Interpolating Polynomial121#include "nrutil.h"s=vector(0,n);for (i=0;i<=n;i++) s[i]=cof[i]=0.0;s[n] = -x[0];for (i=1;i<=n;i++) {Coefficients si of the master polynomial P (x) arefor (j=n-i;j<=n-1;j++)found by recurrence.s[j] -= x[i]*s[j+1];s[n] -= x[i];}for (j=0;j<=n;j++) {phi=n+1;Qfor (k=n;k>=1;k--)The quantity phi = j6=k (xj − xk ) is found as aphi=k*s[k]+x[j]*phi;derivative of P (xj ).ff=y[j]/phi;b=1.0;Coefficients of polynomials in each term of the Lagrange formula are found by synthetic division offor (k=n;k>=0;k--) {P (x) by (x − xj ).

The solution ck is accumucof[k] += b*ff;b=s[k]+x[j]*b;lated.}}free_vector(s,0,n);}Another MethodAnother technique is to make use of the function value interpolation routinealready given (polint §3.1). If we interpolate (or extrapolate) to find the value ofthe interpolating polynomial at x = 0, then this value will evidently be c0 . Nowwe can subtract c0 from the yi ’s and divide each by its corresponding xi . Throwingout one point (the one with smallest xi is a good candidate), we can repeat theprocedure to find c1 , and so on.It is not instantly obvious that this procedure is stable, but we have generallyfound it to be somewhat more stable than the routine immediately preceding. Thismethod is of order N 3 , while the preceding one was of order N 2 . You willfind, however, that neither works very well for large N , because of the intrinsicill-condition of the Vandermonde problem.

In single precision, N up to 8 or 10 issatisfactory; about double this in double precision.#include <math.h>#include "nrutil.h"void polcof(float xa[], float ya[], int n, float cof[])Given arrays xa[0..n] and ya[0..n] containing a tabulated function yai = f (xai ), thisPjroutine returns an array of coefficients cof[0..n] such that yai = j cofj xai .{void polint(float xa[], float ya[], int n, float x, float *y, float *dy);int k,j,i;float xmin,dy,*x,*y;Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).void polcoe(float x[], float y[], int n, float cof[])Given arrays x[0..n] and y[0..n] containing a tabulated function yi = f (xi ), this routinePreturns an array of coefficients cof[0..n], such that yi = j cofj xji .{int k,j,i;float phi,ff,b,*s;122Chapter 3.Interpolation and Extrapolationpolint uses dimensions [1..n].

WeFind the remaining xi of smallestabsolute value,(meanwhile reducing all the terms)and eliminate it.}If the point x = 0 is not in (or at least close to) the range of the tabulated xi ’s,then the coefficients of the interpolating polynomial will in general become very large.However, the real “information content” of the coefficients is in small differencesfrom the “translation-induced” large values. This is one cause of ill-conditioning,resulting in loss of significance and poorly determined coefficients.

You shouldconsider redefining the origin of the problem, to put x = 0 in a sensible place.Another pathology is that, if too high a degree of interpolation is attempted ona smooth function, the interpolating polynomial will attempt to use its high-degreecoefficients, in combinations with large and almost precisely canceling combinations,to match the tabulated values down to the last possible epsilon of accuracy. Thiseffect is the same as the intrinsic tendency of the interpolating polynomial values tooscillate (wildly) between its constrained points, and would be present even if themachine’s floating precision were infinitely good. The above routines polcoe andpolcof have slightly different sensitivities to the pathologies that can occur.Are you still quite certain that using the coefficients is a good idea?CITED REFERENCES AND FURTHER READING:Isaacson, E., and Keller, H.B. 1966, Analysis of Numerical Methods (New York: Wiley), §5.2.Sample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).x=vector(0,n);y=vector(0,n);for (j=0;j<=n;j++) {x[j]=xa[j];y[j]=ya[j];}for (j=0;j<=n;j++) {polint(x-1,y-1,n+1-j,0.0,&cof[j],&dy);Subtract 1 from the pointers to x and y becauseextrapolate to x = 0.xmin=1.0e38;k = -1;for (i=0;i<=n-j;i++) {if (fabs(x[i]) < xmin) {xmin=fabs(x[i]);k=i;}if (x[i]) y[i]=(y[i]-cof[j])/x[i];}for (i=k+1;i<=n-j;i++) {y[i-1]=y[i];x[i-1]=x[i];}}free_vector(y,0,n);free_vector(x,0,n);1233.6 Interpolation in Two or More Dimensions3.6 Interpolation in Two or More Dimensionsya[j][k] = y(x1a[j], x2a[k])(3.6.1)We want to estimate, by interpolation, the function y at some untabulated point(x1 , x2 ).An important concept is that of the grid square in which the point (x1 , x2 )falls, that is, the four tabulated points that surround the desired interior point.

Forconvenience, we will number these points from 1 to 4, counterclockwise startingfrom the lower left (see Figure 3.6.1). More precisely, ifx1a[j] ≤ x1 ≤ x1a[j+1]x2a[k] ≤ x2 ≤ x2a[k+1](3.6.2)defines j and k, theny1 ≡ ya[j][k]y2 ≡ ya[j+1][k]y3 ≡ ya[j+1][k+1](3.6.3)y4 ≡ ya[j][k+1]The simplest interpolation in two dimensions is bilinear interpolation on thegrid square. Its formulas are:t ≡ (x1 − x1a[j])/(x1a[j+1] − x1a[j])u ≡ (x2 − x2a[k])/(x2a[k+1] − x2a[k])(3.6.4)(so that t and u each lie between 0 and 1), andy(x1 , x2) = (1 − t)(1 − u)y1 + t(1 − u)y2 + tuy3 + (1 − t)uy4(3.6.5)Bilinear interpolation is frequently “close enough for government work.” Asthe interpolating point wanders from grid square to grid square, the interpolatedSample page from NUMERICAL RECIPES IN C: THE ART OF SCIENTIFIC COMPUTING (ISBN 0-521-43108-5)Copyright (C) 1988-1992 by Cambridge University Press.Programs Copyright (C) 1988-1992 by Numerical Recipes Software.Permission is granted for internet users to make one paper copy for their own personal use.

Further reproduction, or any copying of machinereadable files (including this one) to any servercomputer, is strictly prohibited. To order Numerical Recipes books,diskettes, or CDROMsvisit website http://www.nr.com or call 1-800-872-7423 (North America only),or send email to trade@cup.cam.ac.uk (outside North America).In multidimensional interpolation, we seek an estimate of y(x1 , x2 , . . . , xn )from an n-dimensional grid of tabulated values y and n one-dimensional vectors giving the tabulated values of each of the independent variables x1 , x2, . .

. ,xn . We will not here consider the problem of interpolating on a mesh that is notCartesian, i.e., has tabulated function values at “random” points in n-dimensionalspace rather than at the vertices of a rectangular array. For clarity, we will considerexplicitly only the case of two dimensions, the cases of three or more dimensionsbeing analogous in every way.In two dimensions, we imagine that we are given a matrix of functional valuesya[1..m][1..n].

We are also given an array x1a[1..m], and an array x2a[1..n].The relation of these input quantities to an underlying function y(x1 , x2 ) is.

Характеристики

Тип файла
PDF-файл
Размер
124,44 Kb
Материал
Тип материала
Высшее учебное заведение

Тип файла PDF

PDF-формат наиболее широко используется для просмотра любого типа файлов на любом устройстве. В него можно сохранить документ, таблицы, презентацию, текст, чертежи, вычисления, графики и всё остальное, что можно показать на экране любого устройства. Именно его лучше всего использовать для печати.

Например, если Вам нужно распечатать чертёж из автокада, Вы сохраните чертёж на флешку, но будет ли автокад в пункте печати? А если будет, то нужная версия с нужными библиотеками? Именно для этого и нужен формат PDF - в нём точно будет показано верно вне зависимости от того, в какой программе создали PDF-файл и есть ли нужная программа для его просмотра.

Список файлов книги

Свежие статьи
Популярно сейчас
Зачем заказывать выполнение своего задания, если оно уже было выполнено много много раз? Его можно просто купить или даже скачать бесплатно на СтудИзбе. Найдите нужный учебный материал у нас!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6309
Авторов
на СтудИзбе
313
Средний доход
с одного платного файла
Обучение Подробнее