c16-1 (779593)

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

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

710Chapter 16.Integration of Ordinary Differential EquationsCITED REFERENCES AND FURTHER READING:Gear, C.W. 1971, Numerical Initial Value Problems in Ordinary Differential Equations (EnglewoodCliffs, NJ: Prentice-Hall).Acton, F.S. 1970, Numerical Methods That Work; 1990, corrected edition (Washington: Mathematical Association of America), Chapter 5.Lambert, J. 1973, Computational Methods in Ordinary Differential Equations (New York: Wiley).Lapidus, L., and Seinfeld, J.

1971, Numerical Solution of Ordinary Differential Equations (NewYork: Academic Press).16.1 Runge-Kutta MethodThe formula for the Euler method isyn+1 = yn + hf(xn , yn )(16.1.1)which advances a solution from xn to xn+1 ≡ xn +h. The formula is unsymmetrical:It advances the solution through an interval h, but uses derivative information onlyat the beginning of that interval (see Figure 16.1.1). That means (and you can verifyby expansion in power series) that the step’s error is only one power of h smallerthan the correction, i.e O(h2 ) added to (16.1.1).There are several reasons that Euler’s method is not recommended for practicaluse, among them, (i) the method is not very accurate when compared to other,fancier, methods run at the equivalent stepsize, and (ii) neither is it very stable(see §16.6 below).Consider, however, the use of a step like (16.1.1) to take a “trial” step to themidpoint of the interval.

Then use the value of both x and y at that midpointto compute the “real” step across the whole interval. Figure 16.1.2 illustrates theidea. In equations,k1 = hf(xn , yn )k2 = hf xn + 12 h, yn + 12 k1(16.1.2)yn+1 = yn + k2 + O(h3 )As indicated in the error term, this symmetrization cancels out the first-order errorterm, making the method second order.

[A method is conventionally called nthorder if its error term is O(hn+1 ).] In fact, (16.1.2) is called the second-orderRunge-Kutta or midpoint method.We needn’t stop there. There are many ways to evaluate the right-hand sidef(x, y) that all agree to first order, but that have different coefficients of higher-ordererror terms. Adding up the right combination of these, we can eliminate the errorterms order by order. That is the basic idea of the Runge-Kutta method. Abramowitzand Stegun [1], and Gear [2], give various specific formulas that derive from this basicSample 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).Stoer, J., and Bulirsch, R. 1980, Introduction to Numerical Analysis (New York: Springer-Verlag),Chapter 7.71116.1 Runge-Kutta Methody(x)21x3xFigure 16.1.1.

Euler’s method. In this simplest (and least accurate) method for integrating an ODE,the derivative at the starting point of each interval is extrapolated to find the next function value. Themethod has first-order accuracy.y(x)421x135x2x3xFigure 16.1.2. Midpoint method. Second-order accuracy is obtained by using the initial derivative ateach step to find a point halfway across the interval, then using the midpoint derivative across the fullwidth of the interval. In the figure, filled dots represent final function values, while open dots representfunction values that are discarded once their derivatives have been calculated and used.idea. By far the most often used is the classical fourth-order Runge-Kutta formula,which has a certain sleekness of organization about it:k1 = hf(xn , yn )hk1k2 = hf(xn + , yn + )22hk2k3 = hf(xn + , yn + )22k4 = hf(xn + h, yn + k3 )k2k3 k4k1++++ O(h5 )yn+1 = yn +6336(16.1.3)The fourth-order Runge-Kutta method requires four evaluations of the righthand side per step h (see Figure 16.1.3).

This will be superior to the midpoint method(16.1.2) if at least twice as large a step is possible with (16.1.3) for the same accuracy.Is that so? The answer is: often, perhaps even usually, but surely not always! Thistakes us back to a central theme, namely that high order does not always meanhigh accuracy. The statement “fourth-order Runge-Kutta is generally superior tosecond-order” is a true one, but you should recognize it as a statement about theSample 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).x2x1712Chapter 16.Integration of Ordinary Differential Equations1yn2yn + 14Figure 16.1.3. Fourth-order Runge-Kutta method.

In each step the derivative is evaluated four times:once at the initial point, twice at trial midpoints, and once at a trial endpoint. From these derivatives thefinal function value (shown as a filled dot) is calculated. (See text for details.)contemporary practice of science rather than as a statement about strict mathematics.That is, it reflects the nature of the problems that contemporary scientists like to solve.For many scientific users, fourth-order Runge-Kutta is not just the first word onODE integrators, but the last word as well. In fact, you can get pretty far on this oldworkhorse, especially if you combine it with an adaptive stepsize algorithm. Keepin mind, however, that the old workhorse’s last trip may well be to take you to thepoorhouse: Bulirsch-Stoer or predictor-corrector methods can be very much moreefficient for problems where very high accuracy is a requirement.

Those methodsare the high-strung racehorses. Runge-Kutta is for ploughing the fields. However,even the old workhorse is more nimble with new horseshoes. In §16.2 we will givea modern implementation of a Runge-Kutta method that is quite competitive as longas very high accuracy is not required. An excellent discussion of the pitfalls inconstructing a good Runge-Kutta code is given in [3].Here is the routine for carrying out one classical Runge-Kutta step on a setof n differential equations. You input the values of the independent variables, andyou get out new values which are stepped by a stepsize h (which can be positive ornegative). You will notice that the routine requires you to supply not only functionderivs for calculating the right-hand side, but also values of the derivatives at thestarting point.

Why not let the routine call derivs for this first value? The answerwill become clear only in the next section, but in brief is this: This call may notbe your only one with these starting conditions. You may have taken a previousstep with too large a stepsize, and this is your replacement. In that case, you do notwant to call derivs unnecessarily at the start. Note that the routine that followshas, therefore, only three calls to derivs.#include "nrutil.h"void rk4(float y[], float dydx[], int n, float x, float h, float yout[],void (*derivs)(float, float [], float []))Given values for the variables y[1..n] and their derivatives dydx[1..n] known at x, use thefourth-order Runge-Kutta method to advance the solution over an interval h and return theincremented variables as yout[1..n], which need not be a distinct array from y.

The usersupplies the routine derivs(x,y,dydx), which returns derivatives dydx at x.{int i;float xh,hh,h6,*dym,*dyt,*yt;dym=vector(1,n);dyt=vector(1,n);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.

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

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

Тип файла PDF

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

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

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

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