c5-11 (779495)

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

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

198Chapter 5.Evaluation of Functionscnst=2.0/(b-a);fac=cnst;for (j=1;j<n;j++) {First we rescale by the factor const...d[j] *= fac;fac *= cnst;}cnst=0.5*(a+b);...which is then redefined as the desired shift.for (j=0;j<=n-2;j++)We accomplish the shift by synthetic division. Syntheticfor (k=n-2;k>=j;k--)division is a miracle of high-school algebra. If youd[k] -= cnst*d[k+1];never learned it, go do so. You won’t be sorry.}CITED REFERENCES AND FURTHER READING:Acton, F.S. 1970, Numerical Methods That Work; 1990, corrected edition (Washington: Mathematical Association of America), pp.

59, 182–183 [synthetic division].5.11 Economization of Power SeriesOne particular application of Chebyshev methods, the economization of power series, isan occasionally useful technique, with a flavor of getting something for nothing.Suppose that you are already computing a function by the use of a convergent powerseries, for examplef (x) ≡ 1 −xx2x3+−+···3!5!7!(5.11.1)√ √(This function is actually sin( x)/ x, but pretend you don’t know that.) You might bedoing a problem that requires evaluating the series many times in some particular interval, say[0, (2π)2 ]. Everything is fine, except that the series requires a large number of terms beforeits error (approximated by the first neglected term, say) is tolerable. In our example, withx = (2π)2 , the first term smaller than 10−7 is x13 /(27!).

This then approximates the errorof the finite series whose last term is x12 /(25!).Notice that because of the large exponent in x13 , the error is much smaller than 10−7everywhere in the interval except at the very largest values of x. This is the feature that allows“economization”: if we are willing to let the error elsewhere in the interval rise to about thesame value that the first neglected term has at the extreme end of the interval, then we canreplace the 13-term series by one that is significantly shorter.Here are the steps for doing so:1.

Change variables from x to y, as in equation (5.8.10), to map the x interval into−1 ≤ y ≤ 1.2. Find the coefficients of the Chebyshev sum (like equation 5.8.8) that exactly equals yourtruncated power series (the one with enough terms for accuracy).3. Truncate this Chebyshev series to a smaller number of terms, using the coefficient of thefirst neglected Chebyshev polynomial as an estimate of the error.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 pcshft(float a, float b, float d[], int n)Polynomial coefficient shift. Given a coefficient array d[0..n-1], this routine generates aPPn-1kkcoefficient array g [0..n-1] such that n-1k=0 dk y =k=0 gk x , where x and y are relatedby (5.8.10), i.e., the interval −1 < y < 1 is mapped to the interval a < x < b. The arrayg is returned in d.{int k,j;float fac,cnst;5.11 Economization of Power Series1994. Convert back to a polynomial in y.5. Change variables back to x.All of these steps can be done numerically, given the coefficients of the original powerseries expansion.

The first step is exactly the inverse of the routine pcshft (§5.10), whichmapped a polynomial from y (in the interval [−1, 1]) to x (in the interval [a, b]). But sinceequation (5.8.10) is a linear relation between x and y, one can also use pcshft for theinverse. The inverse ofturns out to be (you can check this)!−2 − b − a 2 − b − apcshft,,d,nb−ab−aThe second step requires the inverse operation to that done by the routine chebpc (whichtook Chebyshev coefficients into polynomial coefficients).

The following routine, pccheb,accomplishes this, using the formula [1]"!!#1kkkx = k−1 Tk (x) +Tk−2 (x) +Tk−4 (x) + · · ·(5.11.2)122where the last term depends on whether k is even or odd,!!k1 k··· +T1 (x) (k odd),T0 (x) (k even).··· +(k − 1)/22 k/2(5.11.3)void pccheb(float d[], float c[], int n)Inverse of routine chebpc: given an array of polynomial coefficients d[0..n-1], returns anequivalent array of Chebyshev coefficients c[0..n-1].{int j,jm,jp,k;float fac,pow;pow=1.0;Will be powers of 2.c[0]=2.0*d[0];for (k=1;k<n;k++) {Loop over orders of x in the polynomial.c[k]=0.0;Zero corresponding order of Chebyshev.fac=d[k]/pow;jm=k;jp=1;for (j=k;j>=0;j-=2,jm--,jp++) {Increment this and lower orders of Chebyshev with the combinatorial coefficent timesd[k]; see text for formula.c[j] += fac;fac *= ((float)jm)/((float)jp);}pow += pow;}}The fourth and fifth steps are accomplished by the routines chebpc and pcshft,respectively.

Here is how the procedure looks all together: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).pcshft(a,b,d,n)200Chapter 5.Evaluation of Functions#define NFEW ..#define NMANY ..float *c,*d,*e,a,b;Economize NMANY power series coefficients e[0..NMANY-1] in the range (a, b) into NFEWcoefficients d[0..NFEW-1].In our example, by the way, the 8th through 10th Chebyshev coefficients turn out tobe on the order of −7 × 10−6 , 3 × 10−7 , and −9 × 10−9 , so reasonable truncations (forsingle precision calculations) are somewhere in this range, yielding a polynomial with 8 –10 terms instead of the original 13.Replacing a 13-term polynomial with a (say) 10-term polynomial without any loss ofaccuracy — that does seem to be getting something for nothing.

Is there some magic inthis technique? Not really. The 13-term polynomial defined a function f (x). Equivalent toeconomizing the series, we could instead have evaluated f (x) at enough points to constructits Chebyshev approximation in the interval of interest, by the methods of §5.8. We wouldhave obtained just the same lower-order polynomial. The principal lesson is that the rateof convergence of Chebyshev coefficients has nothing to do with the rate of convergence ofpower series coefficients; and it is the former that dictates the number of terms needed in apolynomial approximation.

A function might have a divergent power series in some regionof interest, but if the function itself is well-behaved, it will have perfectly good polynomialapproximations. These can be found by the methods of §5.8, but not by economization ofseries. There is slightly less to economization of series than meets the eye.CITED REFERENCES AND FURTHER READING:Acton, F.S. 1970, Numerical Methods That Work; 1990, corrected edition (Washington: Mathematical Association of America), Chapter 12.Arfken, G. 1970, Mathematical Methods for Physicists, 2nd ed. (New York: Academic Press),p. 631.

[1]5.12 Padé ApproximantsA Padé approximant, so called, is that rational function (of a specified order) whosepower series expansion agrees with a given power series to the highest possible order. Ifthe rational function isMXR(x) ≡ak xkk=01+NXk=1(5.12.1)bk xkSample 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).c=vector(0,NMANY-1);d=vector(0,NFEW-1);e=vector(0,NMANY-1);pcshft((-2.0-b-a)/(b-a),(2.0-b-a)/(b-a),e,NMANY);pccheb(e,c,NMANY);...Here one would normally examine the Chebyshev coefficients c[0..NMANY-1] to decidehow small NFEW can be.chebpc(c,d,NFEW);pcshft(a,b,d,NFEW);.

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

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

Тип файла PDF

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

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

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

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