c5-4 (779488)

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

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

176Chapter 5.Evaluation of FunctionsRational FunctionsYou evaluate a rational function likeR(x) =(5.3.4)in the obvious way, namely as two separate polynomials followed by a divide. As amatter of convention one usually chooses q0 = 1, obtained by dividing numeratorand denominator by any other q0 . It is often convenient to have both sets ofcoefficients stored in a single array, and to have a standard function available fordoing the evaluation:double ratval(double x, double cof[], int mm, int kk)Given mm, kk, and cof[0..mm+kk], evaluate and return the rational function (cof[0] +cof[1]x + · · · + cof[mm]xmm )/(1 + cof[mm+1]x + · · · + cof[mm+kk]xkk ).{int j;double sumd,sumn;Note precision! Change to float if desired.for (sumn=cof[mm],j=mm-1;j>=0;j--) sumn=sumn*x+cof[j];for (sumd=0.0,j=mm+kk;j>=mm+1;j--) sumd=(sumd+cof[j])*x;return sumn/(1.0+sumd);}CITED REFERENCES AND FURTHER READING:Acton, F.S.

1970, Numerical Methods That Work; 1990, corrected edition (Washington: Mathematical Association of America), pp. 183, 190. [1]Mathews, J., and Walker, R.L. 1970, Mathematical Methods of Physics, 2nd ed. (Reading, MA:W.A. Benjamin/Addison-Wesley), pp. 361–363. [2]Knuth, D.E. 1981, Seminumerical Algorithms, 2nd ed., vol. 2 of The Art of Computer Programming(Reading, MA: Addison-Wesley), §4.6. [3]Fike, C.T. 1968, Computer Evaluation of Mathematical Functions (Englewood Cliffs, NJ: PrenticeHall), Chapter 4.Winograd, S. 1970, Communications on Pure and Applied Mathematics, vol. 23, pp.

165–179. [4]Kronsjö, L. 1987, Algorithms: Their Complexity and Efficiency, 2nd ed. (New York: Wiley). [5]5.4 Complex ArithmeticAs we mentioned in §1.2, the lack of built-in complex arithmetic in C is anuisance for numerical work. Even in languages like FORTRAN that have complexdata types, it is disconcertingly common to encounter complex operations thatproduce overflows or underflows when both the complex operands and the complexresult are perfectly representable. This occurs, we think, because software companiesassign inexperienced programmers to what they believe to be the perfectly trivialtask of implementing complex arithmetic.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).p 0 + p1 x + · · · + pµ x µPµ (x)=Qν (x)q 0 + q 1 x + · · · + q ν xν1775.4 Complex ArithmeticActually, complex arithmetic is not quite trivial. Addition and subtractionare done in the obvious way, performing the operation separately on the real andimaginary parts of the operands.

Multiplication can also be done in the obvious way,with 4 multiplications, one addition, and one subtraction,(5.4.1)(the addition before the i doesn’t count; it just separates the real and imaginary partsnotationally). But it is sometimes faster to multiply via(a + ib)(c + id) = (ac − bd) + i[(a + b)(c + d) − ac − bd](5.4.2)which has only three multiplications (ac, bd, (a + b)(c + d)), plus two additions andthree subtractions. The total operations count is higher by two, but multiplicationis a slow operation on some machines.While it is true that intermediate results in equations (5.4.1) and (5.4.2) canoverflow even when the final result is representable, this happens only when the finalanswer is on the edge of representability.

Not so for the complex modulus, if youare misguided enough to compute it as|a + ib| =pa2 + b 2(bad!)(5.4.3)whose intermediate result will overflow if either a or b is as large as the squareroot of the largest representable number (e.g., 1019 as compared to 1038 ). The rightway to do the calculation is|a + ib| =p|a|p 1 + (b/a)2|b| 1 + (a/b)2|a| ≥ |b||a| < |b|(5.4.4)Complex division should use a similar trick to prevent avoidable overflows,underflow, or loss of precision,[a + b(d/c)] + i[b − a(d/c)]a + ib c + d(d/c)=[a(c/d)+b] + i[b(c/d) − a]c + id c(c/d) + d|c| ≥ |d|(5.4.5)|c| < |d|Of course you should calculate repeated subexpressions, like c/d or d/c, only once.Complex square root is even more complicated, since we must both guardintermediate results, and also enforce a chosen branch cut (here taken to be thenegative real axis).

To take the square root of c + id, first compute0 sp2p |c| 1 + 1 + (d/c)2w≡spp|c/d| + 1 + (c/d)2 |d|2c=d=0|c| ≥ |d||c| < |d|(5.4.6)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).(a + ib)(c + id) = (ac − bd) + i(bc + ad)178Chapter 5.Evaluation of FunctionsThen the answer is√0 w=0dw+iw=6 0, c ≥ 02wc + id =w 6= 0, c < 0, d ≥ 0(5.4.7)w 6= 0, c < 0, d < 0Routines implementing these algorithms are listed in Appendix C.CITED REFERENCES AND FURTHER READING:Midy, P., and Yakovlev, Y. 1991, Mathematics and Computers in Simulation, vol.

33, pp. 33–49.Knuth, D.E. 1981, Seminumerical Algorithms, 2nd ed., vol. 2 of The Art of Computer Programming(Reading, MA: Addison-Wesley) [see solutions to exercises 4.2.1.16 and 4.6.4.41].5.5 Recurrence Relations and Clenshaw’sRecurrence FormulaMany useful functions satisfy recurrence relations, e.g.,(n + 1)Pn+1 (x) = (2n + 1)xPn (x) − nPn−1 (x)Jn+1 (x) =2nJn (x) − Jn−1 (x)x(5.5.1)(5.5.2)nEn+1 (x) = e−x − xEn (x)(5.5.3)cos nθ = 2 cos θ cos(n − 1)θ − cos(n − 2)θ(5.5.4)sin nθ = 2 cos θ sin(n − 1)θ − sin(n − 2)θ(5.5.5)where the first three functions are Legendre polynomials, Bessel functions of the firstkind, and exponential integrals, respectively.

(For notation see [1].) These relationsare useful for extending computational methods from two successive values of n toother values, either larger or smaller.Equations (5.5.4) and (5.5.5) motivate us to say a few words about trigonometricfunctions. If your program’s running time is dominated by evaluating trigonometricfunctions, you are probably doing something wrong. Trig functions whose argumentsform a linear sequence θ = θ0 + nδ, n = 0, 1, 2, .

. ., are efficiently calculated bythe following recurrence,cos(θ + δ) = cos θ − [α cos θ + β sin θ]sin(θ + δ) = sin θ − [α sin θ − β cos θ](5.5.6)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).|d|+ iw 2w |d| − iw2w.

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

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

Тип файла PDF

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

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

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

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