c10-1 (Numerical Recipes in C), страница 2

PDF-файл c10-1 (Numerical Recipes in C), страница 2 Цифровая обработка сигналов (ЦОС) (15314): Книга - 8 семестрc10-1 (Numerical Recipes in C) - PDF, страница 2 (15314) - СтудИзба2017-12-27СтудИзба

Описание файла

Файл "c10-1" внутри архива находится в папке "Numerical Recipes in C". PDF-файл из архива "Numerical Recipes in C", который расположен в категории "". Всё это находится в предмете "цифровая обработка сигналов (цос)" из 8 семестр, которые можно найти в файловом архиве МГТУ им. Н.Э.Баумана. Не смотря на прямую связь этого архива с МГТУ им. Н.Э.Баумана, его также можно найти и в других разделах. Архив можно найти в разделе "книги и методические указания", в предмете "цифровая обработка сигналов" в общих файлах.

Просмотр PDF-файла онлайн

Текст 2 страницы из PDF

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).b−a=wc−a400Chapter 10.Minimization or Maximization of FunctionsRoutine for Initially Bracketing a MinimumThe preceding discussion has assumed that you are able to bracket the minimumin the first place.

We consider this initial bracketing to be an essential part of anyone-dimensional minimization. There are some one-dimensional algorithms thatdo not require a rigorous initial bracketing. However, we would never trade thesecure feeling of knowing that a minimum is “in there somewhere” for the dubiousreduction of function evaluations that these nonbracketing routines may promise.Please bracket your minima (or, for that matter, your zeros) before isolating them!There is not much theory as to how to do this bracketing. Obviously you wantto step downhill.

But how far? We like to take larger and larger steps, starting withsome (wild?) initial guess and then increasing the stepsize at each step either bya constant factor, or else by the result of a parabolic extrapolation of the precedingpoints that is designed to take us to the extrapolated turning point. It doesn’t muchmatter if the steps get big. After all, we are stepping downhill, so we already havethe left and middle points of the bracketing triplet. We just need to take a big enoughstep to stop the downhill trend and get a high third point.Our standard routine is this:#include <math.h>#include "nrutil.h"#define GOLD 1.618034#define GLIMIT 100.0#define TINY 1.0e-20#define SHFT(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);Here GOLD is the default ratio by which successive intervals are magnified; GLIMIT is themaximum magnification allowed for a parabolic-fit step.void mnbrak(float *ax, float *bx, float *cx, float *fa, float *fb, float *fc,float (*func)(float))Given a function func, and given distinct initial points ax and bx, this routine searches inthe downhill direction (defined by the function as evaluated at the initial points) and returnsnew points ax, bx, cx that bracket a minimum of the function.

Also returned are the functionvalues at the three points, fa, fb, and fc.{float ulim,u,r,q,fu,dum;*fa=(*func)(*ax);*fb=(*func)(*bx);if (*fb > *fa) {Switch roles of a and b so that we can goSHFT(dum,*ax,*bx,dum)downhill in the direction from a to b.SHFT(dum,*fb,*fa,dum)}*cx=(*bx)+GOLD*(*bx-*ax);First guess for c.*fc=(*func)(*cx);while (*fb > *fc) {Keep returning here until we bracket.r=(*bx-*ax)*(*fb-*fc);Compute u by parabolic extrapolation fromq=(*bx-*cx)*(*fb-*fa);a, b, c. TINY is used to prevent any posu=(*bx)-((*bx-*cx)*q-(*bx-*ax)*r)/sible division by zero.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).just 0.61803 times the size of the preceding interval. This is comparable to, but notquite as good as, the 0.50000 that holds when finding roots by bisection. Note thatthe convergence is linear (in the language of Chapter 9), meaning that successivesignificant figures are won linearly with additional function evaluations.

In thenext section we will give a superlinear method, where the rate at which successivesignificant figures are liberated increases with each successive function evaluation.10.1 Golden Section Search in One Dimension401}}(Because of the housekeeping involved in moving around three or four points andtheir function values, the above program ends up looking deceptively formidable.That is true of several other programs in this chapter as well. The underlying ideas,however, are quite simple.)Routine for Golden Section Search#include <math.h>#define R 0.61803399The golden ratios.#define C (1.0-R)#define SHFT2(a,b,c) (a)=(b);(b)=(c);#define SHFT3(a,b,c,d) (a)=(b);(b)=(c);(c)=(d);float golden(float ax, float bx, float cx, float (*f)(float), float tol,float *xmin)Given a function f, and given a bracketing triplet of abscissas ax, bx, cx (such that bx isbetween ax and cx, and f(bx) is less than both f(ax) and f(cx)), this routine performs agolden section search for the minimum, isolating it to a fractional precision of about tol.

Theabscissa of the minimum is returned as xmin, and the minimum function value is returned asgolden, the returned function value.{float f1,f2,x0,x1,x2,x3;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).(2.0*SIGN(FMAX(fabs(q-r),TINY),q-r));ulim=(*bx)+GLIMIT*(*cx-*bx);We won’t go farther than this. Test various possibilities:if ((*bx-u)*(u-*cx) > 0.0) {Parabolic u is between b and c: try it.fu=(*func)(u);if (fu < *fc) {Got a minimum between b and c.*ax=(*bx);*bx=u;*fa=(*fb);*fb=fu;return;} else if (fu > *fb) {Got a minimum between between a and u.*cx=u;*fc=fu;return;}u=(*cx)+GOLD*(*cx-*bx);Parabolic fit was no use.

Use default magfu=(*func)(u);nification.} else if ((*cx-u)*(u-ulim) > 0.0) {Parabolic fit is between c and itsfu=(*func)(u);allowed limit.if (fu < *fc) {SHFT(*bx,*cx,u,*cx+GOLD*(*cx-*bx))SHFT(*fb,*fc,fu,(*func)(u))}} else if ((u-ulim)*(ulim-*cx) >= 0.0) {Limit parabolic u to maximumu=ulim;allowed value.fu=(*func)(u);} else {Reject parabolic u, use default magnificau=(*cx)+GOLD*(*cx-*bx);tion.fu=(*func)(u);}SHFT(*ax,*bx,*cx,u)Eliminate oldest point and continue.SHFT(*fa,*fb,*fc,fu)402Chapter 10.Minimization or Maximization of Functions}10.2 Parabolic Interpolation and Brent’sMethod in One DimensionWe already tipped our hand about the desirability of parabolic interpolation inthe previous section’s mnbrak routine, but it is now time to be more explicit.

Agolden section search is designed to handle, in effect, the worst possible case offunction minimization, with the uncooperative minimum hunted down and corneredlike a scared rabbit. But why assume the worst? If the function is nicely parabolicnear to the minimum — surely the generic case for sufficiently smooth functions —then the parabola fitted through any three points ought to take us in a single leapto the minimum, or at least very near to it (see Figure 10.2.1). Since we want tofind an abscissa rather than an ordinate, the procedure is technically called inverseparabolic interpolation.The formula for the abscissa x that is the minimum of a parabola through threepoints f(a), f(b), and f(c) isx=b−1 (b − a)2 [f(b) − f(c)] − (b − c)2 [f(b) − f(a)]2 (b − a)[f(b) − f(c)] − (b − c)[f(b) − f(a)](10.2.1)as you can easily derive.

This formula fails only if the three points are collinear,in which case the denominator is zero (minimum of the parabola is infinitely farSample 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).x0=ax;At any given time we will keep track of fourx3=cx;points, x0,x1,x2,x3.if (fabs(cx-bx) > fabs(bx-ax)) {Make x0 to x1 the smaller segment,x1=bx;x2=bx+C*(cx-bx);and fill in the new point to be tried.} else {x2=bx;x1=bx-C*(bx-ax);}f1=(*f)(x1);The initial function evaluations. Note thatf2=(*f)(x2);we never need to evaluate the functionwhile (fabs(x3-x0) > tol*(fabs(x1)+fabs(x2))) {at the original endpoints.if (f2 < f1) {One possible outcome,SHFT3(x0,x1,x2,R*x1+C*x3)its housekeeping,SHFT2(f1,f2,(*f)(x2))and a new function evaluation.} else {The other outcome,SHFT3(x3,x2,x1,R*x2+C*x0)SHFT2(f2,f1,(*f)(x1))and its new function evaluation.}}Back to see if we are done.if (f1 < f2) {We are done.

Output the best of the two*xmin=x1;current values.return f1;} else {*xmin=x2;return f2;}.

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