Главная » Просмотр файлов » Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C

Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C (523184), страница 69

Файл №523184 Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C (Press, Teukolsly, Vetterling, Flannery - Numerical Recipes in C) 69 страницаPress, Teukolsly, Vetterling, Flannery - Numerical Recipes in C (523184) страница 692013-09-15СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 69)

Nevertheless the following tableis indicative of the relative timings, for typical machines, of the various uniform286Chapter 7.Random Numbersgenerators discussed in this section, plus ran4 from §7.5. Smaller values in the tableindicate faster generators. The generators ranqd1 and ranqd2 refer to the “quickand dirty” generators immediately above.GeneratorRelative Execution Timeran0≡ 1.0ran1ran2ran3≈ 1.3≈ 2.0≈ 0.6ranqd1ranqd2ran4≈ 0.10≈ 0.25≈ 4.0On balance, we recommend ran1 for general use. It is portable, based onPark and Miller’s Minimal Standard generator with an additional shuffle, and has noknown (to us) flaws other than period exhaustion.If you are generating more than 100,000,000 random numbers in a singlecalculation (that is, more than about 5% of ran1’s period), we recommend the useof ran2, with its much longer period.Knuth’s subtractive routine ran3 seems to be the timing winner among portableroutines.

Unfortunately the subtractive method is not so well studied, and not astandard. We like to keep ran3 in reserve for a “second opinion,” substituting it whenwe suspect another generator of introducing unwanted correlations into a calculation.The routine ran4 generates extremely good random deviates, and has someother nice properties, but it is slow. See §7.5 for discussion.Finally, the quick and dirty in-line generators ranqd1 and ranqd2 are very fast,but they are somewhat machine dependent, and at best only as good as a 32-bit linearcongruential generator ever is — in our view not good enough in many situations.We would use these only in very special cases, where speed is critical.CITED REFERENCES AND FURTHER READING:Park, S.K., and Miller, K.W.

1988, Communications of the ACM, vol. 31, pp. 1192–1201. [1]Schrage, L. 1979, ACM Transactions on Mathematical Software, vol. 5, pp. 132–138. [2]Bratley, P., Fox, B.L., and Schrage, E.L. 1983, A Guide to Simulation (New York: SpringerVerlag). [3]Knuth, D.E. 1981, Seminumerical Algorithms, 2nd ed., vol. 2 of The Art of Computer Programming(Reading, MA: Addison-Wesley), §§3.2–3.3. [4]Kahaner, D., Moler, C., and Nash, S.

1989, Numerical Methods and Software (Englewood Cliffs,NJ: Prentice Hall), Chapter 10. [5]L’Ecuyer, P. 1988, Communications of the ACM, vol. 31, pp. 742–774. [6]Forsythe, G.E., Malcolm, M.A., and Moler, C.B. 1977, Computer Methods for MathematicalComputations (Englewood Cliffs, NJ: Prentice-Hall), Chapter 10.7.2 Transformation Method: Exponential and Normal Deviates2877.2 Transformation Method: Exponential andNormal DeviatesIn the previous section, we learned how to generate random deviates witha uniform probability distribution, so that the probability of generating a numberbetween x and x + dx, denoted p(x)dx, is given by0dx 0 < x < 1(7.2.1)p(x)dx =0otherwiseThe probability distribution p(x) is of course normalized, so that& ∞p(x)dx = 1(7.2.2)−∞Now suppose that we generate a uniform deviate x and then take some prescribedfunction of it, y(x).

The probability distribution of y, denoted p(y)dy, is determinedby the fundamental transformation law of probabilities, which is simply|p(y)dy| = |p(x)dx| dx p(y) = p(x) dyor(7.2.3)(7.2.4)Exponential DeviatesAs an example, suppose that y(x) ≡ − ln(x), and that p(x) is as given byequation (7.2.1) for a uniform deviate.

Then dx (7.2.5)p(y)dy = dy = e−y dydywhich is distributed exponentially. This exponential distribution occurs frequentlyin real problems, usually as the distribution of waiting times between independentPoisson-random events, for example the radioactive decay of nuclei. You can alsoeasily see (from 7.2.4) that the quantity y/λ has the probability distribution λe−λy .So we have#include <math.h>float expdev(long *idum)Returns an exponentially distributed, positive, random deviate of unit mean, usingran1(idum) as the source of uniform deviates.{float ran1(long *idum);float dum;dodum=ran1(idum);while (dum == 0.0);return -log(dum);}288Chapter 7.Random Numbers1uniformdeviate inF(y) =⌡⌠0 p(y)dyyxp(y)0ytransformeddeviate outFigure 7.2.1.Transformation method for generating a random deviate y from a known probabilitydistribution p(y).

The indefinite integral of p(y) must be known and invertible. A uniform deviate x ischosen between 0 and 1. Its corresponding y on the definite-integral curve is the desired deviate.Let’s see what is involved in using the above transformation method to generatesome arbitrary desired distribution of y’s, say one with p(y) = f(y) for somepositive function f whose integral is 1. (See Figure 7.2.1.) According to (7.2.4),we need to solve the differential equationdx= f(y)dy(7.2.6)But the solution of this is just x = F (y), where F (y) is the indefinite integral off(y).

The desired transformation which takes a uniform deviate into one distributedas f(y) is thereforey(x) = F −1 (x)(7.2.7)where F −1 is the inverse function to F . Whether (7.2.7) is feasible to implementdepends on whether the inverse function of the integral of f(y) is itself feasible tocompute, either analytically or numerically. Sometimes it is, and sometimes it isn’t.Incidentally, (7.2.7) has an immediate geometric interpretation: Since F (y) isthe area under the probability curve to the left of y, (7.2.7) is just the prescription:choose a uniform random x, then find the value y that has that fraction x ofprobability area to its left, and return the value y.Normal (Gaussian) DeviatesTransformation methods generalize to more than one dimension. If x1 , x2 ,. .

. are random deviates with a joint probability distribution p(x1 , x2 , . . .)dx1 dx2 . . . , and if y1 , y2 , . . . are each functions of all the x’s (same number ofy’s as x’s), then the joint probability distribution of the y’s is ∂(x1 , x2 , . . .) dy1 dy2 . . .(7.2.8)p(y1 , y2 , . . .)dy1 dy2 . .

. = p(x1 , x2 , . . .) ∂(y1 , y2 , . . .) where |∂( )/∂( )| is the Jacobian determinant of the x’s with respect to the y’s(or reciprocal of the Jacobian determinant of the y’s with respect to the x’s).7.2 Transformation Method: Exponential and Normal Deviates289An important example of the use of (7.2.8) is the Box-Muller method forgenerating random deviates with a normal (Gaussian) distribution,21p(y)dy = √ e−y /2 dy2π(7.2.9)Consider the transformation between two uniform deviates on (0,1), x1 , x2 , andtwo quantities y1 , y2 ,(y1 = −2 ln x1 cos 2πx2(7.2.10)(y2 = −2 ln x1 sin 2πx2Equivalently we can write1 22x1 = exp − (y1 + y2 )2y21arctanx2 =2πy1Now the Jacobian determinant can readily be calculated (try it!): ∂x∂x1122∂(x1 , x2) ∂y1 ∂y2 11= ∂x2 ∂x2 = − √ e−y1 /2 √ e−y2 /2∂(y1 , y2 )2π2π∂y1(7.2.11)(7.2.12)∂y2Since this is the product of a function of y2 alone and a function of y1 alone, we seethat each y is independently distributed according to the normal distribution (7.2.9).One further trick is useful in applying (7.2.10).

Suppose that, instead of pickinguniform deviates x1 and x2 in the unit square, we instead pick v1 and v2 as theordinate and abscissa of a random point inside the unit circle around the origin. Thenthe sum of their squares, R2 ≡ v12 +v22 is a uniform deviate, which can be used for x1 ,while the angle that (v1 , v2 ) defines with respect to the v1 axis can serve as the randomangle 2πx2 .

What’s√ the advantage?√ It’s that the cosine and sine in (7.2.10) can nowbe written as v1 / R2 and v2 / R2 , obviating the trigonometric function calls!We thus have#include <math.h>float gasdev(long *idum)Returns a normally distributed deviate with zero mean and unit variance, using ran1(idum)as the source of uniform deviates.{float ran1(long *idum);static int iset=0;static float gset;float fac,rsq,v1,v2;if (*idum < 0) iset=0;if (iset == 0) {do {v1=2.0*ran1(idum)-1.0;v2=2.0*ran1(idum)-1.0;rsq=v1*v1+v2*v2;Reinitialize.We don’t have an extra deviate handy, sopick two uniform numbers in the square extending from -1 to +1 in each direction,see if they are in the unit circle,290Chapter 7.Random Numbers} while (rsq >= 1.0 || rsq == 0.0);and if they are not, try again.fac=sqrt(-2.0*log(rsq)/rsq);Now make the Box-Muller transformation to get two normal deviates. Return one andsave the other for next time.gset=v1*fac;iset=1;Set flag.return v2*fac;} else {We have an extra deviate handy,iset=0;so unset the flag,return gset;and return it.}}See Devroye [1] and Bratley [2] for many additional algorithms.CITED REFERENCES AND FURTHER READING:Devroye, L.

1986, Non-Uniform Random Variate Generation (New York: Springer-Verlag), §9.1.[1]Bratley, P., Fox, B.L., and Schrage, E.L. 1983, A Guide to Simulation (New York: SpringerVerlag). [2]Knuth, D.E. 1981, Seminumerical Algorithms, 2nd ed., vol. 2 of The Art of Computer Programming(Reading, MA: Addison-Wesley), pp. 116ff.7.3 Rejection Method: Gamma, Poisson,Binomial DeviatesThe rejection method is a powerful, general technique for generating randomdeviates whose distribution function p(x)dx (probability of a value occurring betweenx and x + dx) is known and computable.

The rejection method does not requirethat the cumulative distribution function [indefinite integral of p(x)] be readilycomputable, much less the inverse of that function — which was required for thetransformation method in the previous section.The rejection method is based on a simple geometrical argument:Draw a graph of the probability distribution p(x) that you wish to generate, sothat the area under the curve in any range of x corresponds to the desired probabilityof generating an x in that range. If we had some way of choosing a random point intwo dimensions, with uniform probability in the area under your curve, then the xvalue of that random point would have the desired distribution.Now, on the same graph, draw any other curve f(x) which has finite (notinfinite) area and lies everywhere above your original probability distribution.

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

Тип файла
PDF-файл
Размер
5,29 Mb
Тип материала
Учебное заведение
Неизвестно

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

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