c5-6 (779490)

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

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

5.6 Quadratic and Cubic Equations183The solution in such cases is to use an alternative Clenshaw recurrence thatincorporates ck ’s in an upward direction. The relevant equations aref(x) = cN FN (x) − β(N, x)FN−1 (x)yN−1 − FN (x)yN−2(5.5.25)(5.5.26)(5.5.27)The rare case where equations (5.5.25)–(5.5.27) should be used instead ofequations (5.5.21) and (5.5.23) can be detected automatically by testing whetherthe operands in the first sum in (5.5.23) are opposite in sign and nearly equal inmagnitude.

Other than in this special case, Clenshaw’s recurrence is always stable,independent of whether the recurrence for the functions Fk is stable in the upwardor downward direction.CITED REFERENCES AND FURTHER READING:Abramowitz, M., and Stegun, I.A. 1964, Handbook of Mathematical Functions, Applied Mathematics Series, Volume 55 (Washington: National Bureau of Standards; reprinted 1968 byDover Publications, New York), pp. xiii, 697. [1]Gautschi, W. 1967, SIAM Review, vol.

9, pp. 24–82. [2]Lakshmikantham, V., and Trigiante, D. 1988, Theory of Difference Equations: Numerical Methodsand Applications (San Diego: Academic Press). [3]Acton, F.S. 1970, Numerical Methods That Work; 1990, corrected edition (Washington: Mathematical Association of America), pp. 20ff.

[4]Clenshaw, C.W. 1962, Mathematical Tables, vol. 5, National Physical Laboratory (London: H.M.Stationery Office). [5]Dahlquist, G., and Bjorck, A. 1974, Numerical Methods (Englewood Cliffs, NJ: Prentice-Hall),§4.4.3, p. 111.Goodwin, E.T. (ed.) 1961, Modern Computing Methods, 2nd ed. (New York: Philosophical Library), p.

76.5.6 Quadratic and Cubic EquationsThe roots of simple algebraic equations can be viewed as being functions of theequations’ coefficients. We are taught these functions in elementary algebra. Yet,surprisingly many people don’t know the right way to solve a quadratic equationwith two real roots, or to obtain the roots of a cubic equation.There are two ways to write the solution of the quadratic equationax2 + bx + c = 0(5.6.1)with real coefficients a, b, c, namelyx=−b ±√b2 − 4ac2a(5.6.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).y−2 = y−1 = 01[yk−2 − α(k, x)yk−1 − ck ],yk =β(k + 1, x)(k = 0, 1, . . . , N − 1)184Chapter 5.andx=Evaluation of Functions2c√−b ± b2 − 4ac(5.6.3)q≡−ip1hb + sgn(b) b2 − 4ac2(5.6.4)Then the two roots arex1 =qax2 =andcq(5.6.5)If the coefficients a, b, c, are complex rather than real, then the above formulasstill hold, except that in equation (5.6.4) the sign of the square root should bechosen so as to makep(5.6.6)Re(b* b2 − 4ac) ≥ 0where Re denotes the real part and asterisk denotes complex conjugation.Apropos of quadratic equations, this seems a convenient place to recall thatthe inverse hyperbolic functions sinh−1 and cosh−1 are in fact just logarithms ofsolutions to such equations,px2 + 1pcosh−1 (x) = ± ln x + x2 − 1sinh−1 (x) =ln x +(5.6.7)(5.6.8)Equation (5.6.7) is numerically robust for x ≥ 0.

For negative x, use the symmetrysinh−1 (−x) = − sinh−1 (x). Equation (5.6.8) is of course valid only for x ≥ 1.For the cubic equationx3 + ax2 + bx + c = 0(5.6.9)with real or complex coefficients a, b, c, first computeQ≡a2 − 3b9andR≡2a3 − 9ab + 27c54(5.6.10)If Q and R are real (always true when a, b, c are real) and R2 < Q3 , then the cubicequation has three real roots. Find them by computingθ = arccos(R/pQ3 )(5.6.11)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).If you use either (5.6.2) or (5.6.3) to get the two roots, you are asking for trouble: Ifeither a or c (or both) are small, then one of the roots will involve the subtractionof b from a very nearly equal quantity (the discriminant); you will get that root veryinaccurately.

The correct way to compute the roots is1855.6 Quadratic and Cubic Equationsa3a3(5.6.12)(This equation first appears in Chapter VI of François Viète’s treatise “De emendatione,” published in 1615!)Otherwise, computehi1/3pA = − R + R 2 − Q3(5.6.13)where the sign of the square root is chosen to makepRe(R* R2 − Q3 ) ≥ 0(5.6.14)(asterisk again denoting complex conjugation). If Q and R are both real, equations(5.6.13)–(5.6.14) are equivalent toi1/3hp(5.6.15)A = −sgn(R) |R| + R2 − Q3where the positive square root is assumed.

Next computeQ/A(A 6= 0)B=0(A = 0)(5.6.16)in terms of which the three roots arex1 = (A + B) −a3(5.6.17)(the single real root when a, b, c are real) and√a13(A − B)x2 = − (A + B) − + i232(5.6.18)√a13(A − B)x3 = − (A + B) − − i232(in that same case, a complex conjugate pair). Equations (5.6.13)–(5.6.16) arearranged both to minimize roundoff error, and also (as pointed out by A.J. Glassman)to ensure that no choice of branch for the complex cube root can result in thespurious loss of a distinct root.If you need to solve many cubic equations with only slightly different coefficients, it is more efficient to use Newton’s method (§9.4).CITED REFERENCES AND FURTHER READING:Weast, R.C.

(ed.) 1967, Handbook of Tables for Mathematics, 3rd ed. (Cleveland: The ChemicalRubber Co.), pp. 130–133.Pachner, J. 1983, Handbook of Numerical Analysis Applications (New York: McGraw-Hill), §6.1.McKelvey, J.P. 1984, American Journal of Physics, vol. 52, pp. 269–270; see also vol. 53,p. 775, and vol. 55, pp. 374–375.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).in terms of which the three roots are paθ−x1 = −2 Q cos33pθ + 2π−x2 = −2 Q cos3pθ − 2π−x3 = −2 Q cos3186Chapter 5.Evaluation of Functions5.7 Numerical Derivativesf 0 (x) ≈f(x + h) − f(x)h(5.7.1)practically suggests the program: Pick a small value h; evaluate f(x + h); youprobably have f(x) already evaluated, but if not, do it too; finally apply equation(5.7.1).

What more needs to be said?Quite a lot, actually. Applied uncritically, the above procedure is almostguaranteed to produce inaccurate results. Applied properly, it can be the right wayto compute a derivative only when the function f is fiercely expensive to compute,when you already have invested in computing f(x), and when, therefore, you wantto get the derivative in no more than a single additional function evaluation.

In sucha situation, the remaining issue is to choose h properly, an issue we now discuss:There are two sources of error in equation (5.7.1), truncation error and roundofferror. The truncation error comes from higher terms in the Taylor series expansion,11f(x + h) = f(x) + hf 0 (x) + h2 f 00 (x) + h3 f 000 (x) + · · ·26(5.7.2)whence1f(x + h) − f(x)= f 0 + hf 00 + · · ·h2(5.7.3)The roundoff error has various contributions. First there is roundoff error in h:Suppose, by way of an example, that you are at a point x = 10.3 and you blindlychoose h = 0.0001. Neither x = 10.3 nor x + h = 10.30001 is a number withan exact representation in binary; each is therefore represented with some fractionalerror characteristic of the machine’s floating-point format, m , whose value in singleprecision may be ∼ 10−7 .

The error in the effective value of h, namely the differencebetween x + h and x as represented in the machine, is therefore on the order of m x,which implies a fractional error in h of order ∼ m x/h ∼ 10−2 ! By equation (5.7.1)this immediately implies at least the same large fractional error in the derivative.We arrive at Lesson 1: Always choose h so that x + h and x differ by an exactlyrepresentable number.

This can usually be accomplished by the program stepstemp = x + hh = temp − x(5.7.4)Some optimizing compilers, and some computers whose floating-point chips havehigher internal accuracy than is stored externally, can foil this trick; if so, it isusually enough to declare temp as volatile, or else to call a dummy functiondonothing(temp) between the two equations (5.7.4). This forces temp into andout of addressable memory.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).Imagine that you have a procedure which computes a function f(x), and nowyou want to compute its derivative f 0 (x). Easy, right? The definition of thederivative, the limit as h → 0 of.

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

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

Тип файла PDF

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

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

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

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