c15-2 (779586)

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

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

66115.2 Fitting Data to a Straight Lineσ2 =NX[yi − y(xi )]2 /(N − M )(15.1.6)i=1Obviously, this approach prohibits an independent assessment of goodness-of-fit, afact occasionally missed by its adherents. When, however, the measurement erroris not known, this approach at least allows some kind of error bar to be assignedto the points.If we take the derivative of equation (15.1.5) with respect to the parameters ak ,we obtain equations that must hold at the chi-square minimum,0=N Xyi − y(xi )∂y(xi ; . . . ak .

. .)i=1σi2∂akk = 1, . . . , M(15.1.7)Equation (15.1.7) is, in general, a set of M nonlinear equations for the M unknownak . Various of the procedures described subsequently in this chapter derive from(15.1.7) and its specializations.CITED REFERENCES AND FURTHER READING:Bevington, P.R. 1969, Data Reduction and Error Analysis for the Physical Sciences (New York:McGraw-Hill), Chapters 1–4.von Mises, R. 1964, Mathematical Theory of Probability and Statistics (New York: AcademicPress), §VI.C. [1]15.2 Fitting Data to a Straight LineA concrete example will make the considerations of the previous section moremeaningful.

We consider the problem of fitting a set of N data points (xi , yi ) toa straight-line modely(x) = y(x; a, b) = a + bx(15.2.1)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).as a distribution can be. Almost always, the cause of too good a chi-square fitis that the experimenter, in a “fit” of conservativism, has overestimated his or hermeasurement errors.

Very rarely, too good a chi-square signals actual fraud, datathat has been “fudged” to fit the model.A rule of thumb is that a “typical” value of χ2 for a “moderately” good fit is22χ ≈ ν. More√ precise is the statement that the χ statistic has a mean ν and a standarddeviation 2ν, and, asymptotically for large ν, becomes normally distributed.In some cases the uncertainties associated with a set of measurements are notknown in advance, and considerations related to χ2 fitting are used to derive a valuefor σ.

If we assume that all measurements have the same standard deviation, σi = σ,and that the model does fit well, then we can proceed by first assigning an arbitraryconstant σ to all points, next fitting for the model parameters by minimizing χ2 ,and finally recomputing662Chapter 15.Modeling of Data2χ (a, b) =2N Xyi − a − bxiσii=1(15.2.2)If the measurement errors are normally distributed, then this merit function will givemaximum likelihood parameter estimations of a and b; if the errors are not normallydistributed, then the estimations are not maximum likelihood, but may still be usefulin a practical sense.

In §15.7, we will treat the case where outlier points are sonumerous as to render the χ2 merit function useless.Equation (15.2.2) is minimized to determine a and b. At its minimum,derivatives of χ2 (a, b) with respect to a, b vanish.X yi − a − bxi∂χ2= −2∂aσi2N0=i=1NXxi (yi − a − bxi )2∂χ= −20=∂bi=1(15.2.3)σi2These conditions can be rewritten in a convenient form if we define the followingsums:S≡NX1σi2Sx ≡i=1SxxNXxiσi2Sy ≡i=1NXx2i≡σ2i=1 iSxy ≡NXyiσi2i=1NXxi yii=1(15.2.4)σi2With these definitions (15.2.3) becomesaS + bSx = SyaSx + bSxx = Sxy(15.2.5)The solution of these two equations in two unknowns is calculated as∆ ≡ SSxx − (Sx )2Sxx Sy − Sx Sxy∆SSxy − Sx Syb=∆a=(15.2.6)Equation (15.2.6) gives the solution for the best-fit model parameters a and b.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).This problem is often called linear regression, a terminology that originated, longago, in the social sciences. We assume that the uncertainty σi associated witheach measurement yi is known, and that the xi ’s (values of the dependent variable)are known exactly.To measure how well the model agrees with the data, we use the chi-squaremerit function (15.1.5), which in this case is15.2 Fitting Data to a Straight Line663σf2 =NXσi2i=1∂f∂yi2(15.2.7)For the straight line, the derivatives of a and b with respect to yi can be directlyevaluated from the solution:Sxx − Sx xi∂a=∂yiσi2 ∆Sxi − Sx∂b=∂yiσi2 ∆(15.2.8)Summing over the points as in (15.2.7), we getσa2 = Sxx /∆(15.2.9)σb2 = S/∆which are the variances in the estimates of a and b, respectively.

We will see in§15.6 that an additional number is also needed to characterize properly the probableuncertainty of the parameter estimation. That number is the covariance of a and b,and (as we will see below) is given byCov(a, b) = −Sx /∆(15.2.10)The coefficient of correlation between the uncertainty in a and the uncertaintyin b, which is a number between −1 and 1, follows from (15.2.10) (compareequation 14.5.1),−Sxrab = √SSxx(15.2.11)A positive value of rab indicates that the errors in a and b are likely to have thesame sign, while a negative value indicates the errors are anticorrelated, likely tohave opposite signs.We are still not done. We must estimate the goodness-of-fit of the data to themodel.

Absent this estimate, we have not the slightest indication that the parametersa and b in the model have any meaning at all! The probability Q that a value ofchi-square as poor as the value (15.2.2) should occur by chance isQ = gammqN − 2 χ2,22(15.2.12)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).We are not done, however. We must estimate the probable uncertainties inthe estimates of a and b, since obviously the measurement errors in the data mustintroduce some uncertainty in the determination of those parameters. If the dataare independent, then each contributes its own bit of uncertainty to the parameters.Consideration of propagation of errors shows that the variance σf2 in the value ofany function will be664Chapter 15.Modeling of DataIn §14.5 we promised a relation between the linear correlation coefficientr (equation 14.5.1) and a goodness-of-fit measure, χ2 (equation 15.2.2).

Forunweighted data (all σi = 1), that relation isχ2 = (1 − r 2 )NVar (y1 . . . yN )(15.2.13)whereNVar (y1 . . . yN ) ≡NX(yi − y)2(15.2.14)i=1For data with varying weights σi , the above equations remain valid if the sums inequation (14.5.1) are weighted by 1/σi2 .The following function, fit, carries out exactly the operations that we havediscussed.

When the weights σ are known in advance, the calculations exactlycorrespond to the formulas above. However, when weights σ are unavailable,the routine assumes equal values of σ for each point and assumes a good fit, asdiscussed in §15.1.The formulas (15.2.6) are susceptible to roundoff error. Accordingly, werewrite them as follows: Define1Sx,i = 1, 2, . . ., N(15.2.15)xi −ti =σiSandNXStt =t2i(15.2.16)i=1Then, as you can verify by direct substitution,b=N1 X ti yiSttσi(15.2.17)Sy − Sx bS(15.2.18)i=1a=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).Here gammq is our routine for the incomplete gamma function Q(a, x), §6.2. IfQ is larger than, say, 0.1, then the goodness-of-fit is believable.

If it is largerthan, say, 0.001, then the fit may be acceptable if the errors are nonnormal or havebeen moderately underestimated. If Q is less than 0.001 then the model and/orestimation procedure can rightly be called into question. In this latter case, turnto §15.7 to proceed further.If you do not know the individual measurement errors of the points σi , and areproceeding (dangerously) to use equation (15.1.6) for estimating these errors, thenhere is the procedure for estimating the probable uncertainties of the parameters aand b: Set σi ≡ 1 in all equations through (15.2.6), andpmultiply σa and σb , asobtained from equation (15.2.9), by the additional factor χ2 /(N − 2), where χ2is computed by (15.2.2) using the fitted parameters a and b. As discussed above,this procedure is equivalent to assuming a good fit, so you get no independentgoodness-of-fit probability Q.66515.2 Fitting Data to a Straight Line(15.2.19)(15.2.20)(15.2.21)(15.2.22)#include <math.h>#include "nrutil.h"void fit(float x[], float y[], int ndata, float sig[], int mwt, float *a,float *b, float *siga, float *sigb, float *chi2, float *q)Given a set of data points x[1..ndata],y[1..ndata] with individual standard deviationssig[1..ndata], fit them to a straight line y = a + bx by minimizing χ2 .

Returned area,b and their respective probable uncertainties siga and sigb, the chi-square chi2, and thegoodness-of-fit probability q (that the fit would have χ2 this large or larger). If mwt=0 oninput, then the standard deviations are assumed to be unavailable: q is returned as 1.0 andthe normalization of chi2 is to unit standard deviation on all points.{float gammq(float a, float x);int i;float wt,t,sxoss,sx=0.0,sy=0.0,st2=0.0,ss,sigdat;*b=0.0;if (mwt) {ss=0.0;for (i=1;i<=ndata;i++) {wt=1.0/SQR(sig[i]);ss += wt;sx += x[i]*wt;sy += y[i]*wt;}} else {for (i=1;i<=ndata;i++) {sx += x[i];sy += y[i];}ss=ndata;}sxoss=sx/ss;if (mwt) {for (i=1;i<=ndata;i++) {t=(x[i]-sxoss)/sig[i];st2 += t*t;*b += t*y[i]/sig[i];}} else {for (i=1;i<=ndata;i++) {t=x[i]-sxoss;st2 += t*t;*b += t*y[i];}}*b /= st2;*a=(sy-sx*(*b))/ss;*siga=sqrt((1.0+sx*sx/(ss*st2))/ss);*sigb=sqrt(1.0/st2);Accumulate sums ......with weights...or without weights.Solve for a, b, σa , and σb .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.

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

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

Тип файла PDF

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

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

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

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