26
UNIVERSIDAD COMPLUTENSE DE MADRID DEPARTAMENTO DE FISICA TEORICA I MJRPlaza ısica Computacional Los libros de donde se toman los ejercicios est´ an indicados entre corchetes, as´ ı [Knuth] es Knuth, [PTVF] es Press, Teukolsky, Vetterling andFlannery, [FB] es Faires&Burden, [KC] Kincaid&Cheney, etc. La referencia completa est´ a en el programa de la asignatura. Los problemas en rojo se proponen como ejercicios al alumno. Los que no tienen punto unos los hago yo en clase, otros los haremos en el laboratorio de F´ ısica Computacional. Los que sean para entregar al profesor (evaluaci´ on continua) se se˜ nalar´ an a su debido tiempo. Nota muy importante: El profesor, o sea yo, MJRP, no valora los ejercicios que se hacen en grupo o en parejas. Lo que falta de frase, lo dir´ e en clase que se tarda menos. DE RELLENO PERO ´ UTILES 1. (A mano) Convert 729 to binary. Sol: 1011011001 2 . Convert 100111.101 2 to decimal. Sol: 39.625 10 . Convert -21435 8 to binary. 2. (A mano) Escribir como fracci´ on los siguientes n´ umeros racionales: a) 0.6666666 ... , b) 5.137137137 ... , c) 0.999999 ... (el m´ as sorprendente, sin duda alguna). 3. Buscar en Maple los comandos que resuelven los ejercicios anteriores. Pierda en ello un tiempo prudencial, no m´ as. Preg´ unteme si no los encuentra. Compruebe que los resultados son los obtenidos a mano. 4. En la secuencia 10 12 - 1, 10 12 - 2, 10 12 - 3,..., ¿cu´ al es el primer primo? (ver el ejercicio 34) ¿Ha necesitado usted ordenador para averiguarlo? [Yo s´ ı necesit´ e el ordenador. Hab´ ıa dos n´ umeros antes del pedido que no sab´ ıa entre qu´ e di- vidirlos. Y lo mismo aplica para el que pide el ejercicio: que no sab´ ıa si era primo o no. ¿Qu´ e habr´ ıan hecho un Euler o un Gauss en este caso? Pregunta ret´orica, no conteste.] 5. [Experimental Mathematics] Is it true that 2 arctan 2 π = arctan 4π π 2 - 4 , or is it false? Prove one or another with: i) Maple, ii) analitically. C ´ ALCULO DE LOS CEROS DE UNA FUNCI ´ ON 6. Para familiarizarse con el m´ etodo de Newton y el de la Secante coged el Faires&Burden de la biblioteca, y de las secciones 2.3, 2.4 y algo de la 2.5 haced los ejercicios que quer´ ais. Mejor aquellos de los que venga la soluci´ on en el libro o tengan algo interesante (no todos son interesantes). Cuando os salgan, pas´ ais a otra cosa. Los enunciados de los problemas del Kincaid&Cheney est´ an muy bien tambi´ en. 7. [Newton’s method] To approximate numbers such as 3 or 3 25 one calculates the zeros of x 2 - 3, or x 3 - 25, for instance. Resolve both cases with Newton’s method with your own tolerance. Choose the initial point carefully. If we wanted to have a numerical approximation of log 2, would it be possible to write a polyno- mial with integer coefficients such that one of its roots were exactly equal to log 2? Answer:

UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

  • Upload
    others

  • View
    3

  • Download
    0

Embed Size (px)

Citation preview

Page 1: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

UNIVERSIDAD COMPLUTENSE DE MADRID

DEPARTAMENTO DE FISICA TEORICA I

MJRPlaza

Fısica Computacional

Los libros de donde se toman los ejercicios estan indicados entre corchetes, ası [Knuth] es Knuth,[PTVF] es Press, Teukolsky, Vetterling and Flannery, [FB] es Faires&Burden, [KC] Kincaid&Cheney,etc. La referencia completa esta en el programa de la asignatura. Los problemas en rojo se proponencomo ejercicios al alumno. Los que no tienen punto unos los hago yo en clase, otros los haremos en ellaboratorio de Fısica Computacional. Los que sean para entregar al profesor (evaluacion continua)se senalaran a su debido tiempo.

Nota muy importante: El profesor, o sea yo, MJRP, no valora los ejercicios que se hacen en grupoo en parejas. Lo que falta de frase, lo dire en clase que se tarda menos.

DE RELLENO PERO UTILES

1. (A mano) Convert 729 to binary. Sol: 10110110012 . Convert 100111.1012 to decimal. Sol:39.62510. • Convert −214358 to binary.

2. (A mano) Escribir como fraccion los siguientes numeros racionales: a) 0.6666666 . . ., • b)5.137137137 . . ., • c) 0.999999 . . . (el mas sorprendente, sin duda alguna).

3. • Buscar en Maple los comandos que resuelven los ejercicios anteriores. Pierda en ello untiempo prudencial, no mas. Pregunteme si no los encuentra. Compruebe que los resultadosson los obtenidos a mano.

4. • En la secuencia 1012 − 1, 1012 − 2, 1012 − 3, . . ., ¿cual es el primer primo? (ver el ejercicio34) ¿Ha necesitado usted ordenador para averiguarlo?

[Yo sı necesite el ordenador. Habıa dos numeros antes del pedido que no sabıa entre que di-vidirlos. Y lo mismo aplica para el que pide el ejercicio: que no sabıa si era primo o no. ¿Quehabrıan hecho un Euler o un Gauss en este caso? Pregunta retorica, no conteste.]

5. • [Experimental Mathematics] Is it true that 2 arctan2

π= arctan

π2 − 4, or is it false? Prove

one or another with: i) Maple, ii) analitically.

CALCULO DE LOS CEROS DE UNA FUNCION

6. • Para familiarizarse con el metodo de Newton y el de la Secante coged el Faires&Burdende la biblioteca, y de las secciones 2.3, 2.4 y algo de la 2.5 haced los ejercicios que querais.Mejor aquellos de los que venga la solucion en el libro o tengan algo interesante (no todosson interesantes). Cuando os salgan, pasais a otra cosa. Los enunciados de los problemas delKincaid&Cheney estan muy bien tambien.

7. [Newton’s method] To approximate numbers such as√3 or 3

√25 one calculates the zeros of

x2 − 3, or x3 − 25, for instance. Resolve both cases with Newton’s method with your owntolerance. Choose the initial point carefully.

If we wanted to have a numerical approximation of log 2, would it be possible to write a polyno-mial with integer coefficients such that one of its roots were exactly equal to log 2? Answer:

Page 2: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

Table 1:n xn f(xn)

2 1.263157895 -1.6022743793 1.338827839 -0.4303647474 1.366616395 -0.022909445 1.365211902 -0.0002990806 1.365230001 -0.0000002047 1.365230013 -0.000000008

no. The number log 2 is a trascendent number, not an algebraic number. An algebraic numberis a zero of a polynomial of arbitrary degree with integer coefficients.

8. [KC, pg 74] ¿Que calculan los siguientes esquemas numericos? Identifıquelos, si es posible,como la iteracion de Newton de una cierta funcion.

a) xn+1 =23

(

xn +1

x2n

)

, b) xn+1 = xn (2−Rxn).

9. [KC, pg 13] [Curioso] What happens if the Newton iteration is applied to f(x) = arctan x withx0 = 2? For what starting point value will Newton’s method converge?

10. Con Maple. La solucion real de x3 + 4x2 − 10 = 0 es exactamente:

3

71

27+

√105

9+

3

71

27−

√105

9−

4

3.

Encuentrela resolviendo el polinomio (los de grado 3 se resuelven por radicales). Y ya puestos,las complejas conjugadas tambien. El valor exacto de la solucion real con ocho cifras decimales,como usted puede comprobar con Maple (comando fsolve) o utilizando metodos numericos es1.36523001. Usando el metodo de la secante con x0 = 1 y x1 = 2 y tolerancia 10−6 se obtienela Tabla 1. Se trabaja con 10 dıgitos.

11. • [F-B, pag 47] Utilice Maple para determinar cuantas iteraciones del metodo de la secante sonnecesarias para calcular una raız de f(x) = cos x − x con una precision de 10−100 tomandocomo puntos iniciales x0 = 1/2 y x1 = π/4.

Sol: Maple trabaja por defecto con 10 dıgitos y no puede ver de ninguna manera si la diferenciade dos numeros es 10−100 como dice el enunciado (porque ve 0). Cambie entonces el numerode dıgitos a 120, por ejemplo. Necesita 10 iteraciones (el primer x2 lo cuento como primeraiteracion, el libro lo hace como segunda, por el dos del subındice) para alcanzar una toleranciade 10−100. El resultado escrito con 100 cifras es

p = 0.73908513321516064165531208767387340401341175890075746496568063

57732846548835475945993761069317665319.

(lo he escrito con 102 cifras y luego tirado dos para redondear con la ley del 5). O sea, que el19 final viene de redondear 1850.

12. • [Iteration method] In the year 1225 Leonardo of Pisa, also known as Fibonacci, studied theequation

f(x) = x3 + 2x2 + 10x− 20 = 0

and produced p = 1.368 808 107. Nobody knows by what method Leonardo found this valuebut it is a remarkable result for his time. Write the equation in the form x = F (x) with

Page 3: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

F (x) = 20/(x2 + 2x + 10). i) Starting with x0 = 1, how many iterations are necessary toproduce Leonardo’s result? ii) Why is the convergence of the algorithm so slow? iii) Find thatthe real root of Leonardo is exactly

1

3

3

6√3930 + 352 −

1

3

3

6√3930 − 352 −

2

3.

Sol: i) 26. ii) Because en+1 ∼ F ′(p) en (demuestre esto, por favor), i.e. en+1 ∼ 0.44 en and0.44 indicates that are necessary two or three iterations to obtain a new correct decimal place.(Observe that if F ′(p) is near 1 this is slow convergence. And F ′(p) ≥ 1 is no convergence at all)

13. [Bender&Orszag, pg 245] Show that the sequence√7,√

7−√7,

7−√

7−√7, . . . converges

and evaluate the limit [Putnam, 1953].

Sol: Primero se ve a que converge y luego se justifica. Es de aplicaciones contractivas.

14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered at theorigin with all the zeros of the polynomial x4 − 4x3 + 7x2 − 5x− 2.

NONLINEAR ALGEBRAIC EQUATIONS IN SEVERAL VARIABLES

15. Solve the equations x = sin(x+ y), y = cos(x− y).

Sol: Unique solution (plot with Maple). It is the point (0.93508206, 0.99802005) and takes forNewton-Raphson 5 iterations with the choice (x0, y0) = (0.9, 0.7), ten digits accuracy, toler-ance 10−9.

16. Solve the equations x = sinx cosh y, y = cos x sinh y near x = 7., y = 3.. Sol: In this case thereare many solutions, as a Maple plot indicates.

PARA ENTREGAR CUANDO YO LOS PIDA (pedidos el 5 de Diciembre de 2012)

17. • [Kepler’s equation] A very famous equation in Astronomy is Kepler’s equation, s−e sin s = m.It derives from the Second Law of Planetary Motion ‘the line connecting the Sun to a planetsweeps equal areas in equal times’ and involves the ellipse eccentricity, 0 < e < 1, the angle s(see the picture) known as eccentric anomaly and the mean anomaly m, that by definition isequal to m = 2πt/T . The problem is to find s when e and m are known.

x

y

P

s

ae focus

a

b

θ

i) Mathematically speaking for each m in [0, π] there is only one s that satisfies the equation.This is because Kepler equation is a fixed point problem with F (s) ≡ m + e sin s = s. But it

Page 4: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

is not just another fixed point problem: it is a very rich and surprising one. Although no onehas solved it analitically (numerically, yes, of course, and as a power series in e, and relatedto Bessel functions also) try to obtain with Maple a few results. For example, a) set e = 1/2,and construct the sequence F (0), F (F (0)), F (F (F (0))), . . .. Stop when you have applied Fone hundred times (a do will do the job and will do it perfecfly if you write e = 0.5 insteadof 1/2). Expand the result in power series around m = 0 (with the Maple command series

and with truncate order equal to 16, for instance). What is your result? Is it an even functionof m or is it odd? b) Repeat with F (1), F (F (1)), F (F (F (1))), . . .. Expand in a series. Doyou obtain the same series than in a)? You shall obtain the same series! c) Repeat withF (3), F (F (3)), F (F (F (3))), . . .. Expand again. Do you obtain the same series than in a)?Again, you shall obtain the same series since the fixed point is unique. d) Check that in allthe three previous cases the result is

2m−4

3m3 +

44

15m5 −

2696

315m7 +

81068

2835m9 + · · · .

ii) Often Kepler equation is used in the following manner. In its motion around the Sun, thatit is in the focus of an ellipse, the Earth makes one complete orbit in approximately T = 365days. The eccentricity of the ellipse is about 0.0167. Approximately is on January 4 when theEarth approaches closest to the Sun (perihelion occurs approximately on January 4). Now wewe want to know the Earth’s position on February 15, or 41 days since perihelion. Finding theEarth’s position at this time requires solving Kepler’s equation for s. In this case, the Earth isat P and m = 2π · 41/365 ∼ 0.70578. Use Newton’s method to obtain a good approximationfor s solving s − 0.0167 sin s = 0.70578. Just in case you want to know, once s is known the

angle θ is calculated with tanθ

2=

1 + e

1− etan

s

2.

18. • [Pozo finito de potencial-Pozo infinito] Consider an electron in a finite potential well L =0.5 × 10−9 m wide and V0 = 25 eV deep. Obtain the energy levels for this finite well solvingone of the equations (Newton’s method does the job very well)

α tanα =√

α2o − α2, α cotα = −

α2o − α2,

where α2 = meEL2/2~2 and α20 = mec

2V0L2/2~2c2, and compare the results to an equal width

infinite well. The first equation is for even eigenfunctions, the second for odd. Remember fromQuantum Mechanics that the ground state is even, the next state is odd, then follows an evenstate, odd the next one and so on. Notice that the energy levels for the finite well are lessthan the corresponding energies for the infinite well and that the difference becomes greater asthe energy nears the well depth. Besides, a finite well only supports a fixed number of boundstates. In our example this number is 5. And now the last question or how to turn a 5 into a6. Keeping L unchanged modify the value of V0 so that the well has 6 states. What should bethe minimum value of the depth V0 for this to happen?

Here are some useful numbers for your calculations: me = 0.511 × 106 eV/c2, ~ = 6.58 ×10−16 eV s, c = 3 × 108 m s−1, 1 A = 10−10 m. Use a good book of Quantum Mechanics ifyou need particular formulae. Otherwise you might want to deduce them, what is very goodtoo! If your numbers are correct they shall be similar to those in Table 2.

Nota: La anchura del pozo es del orden del A y las energıas del orden del eV (da igual siuno o cincuenta o cien) lo quiere decir que nuestro electron se mueve en un atomo porqueempleamos unidades caracterısticas de atomos y no de nucleos o partıculas elementales. Digoesto porque cantidades como mec

2V0L2/2~2c2 que necesitamos para resolver nuestro problema

son cosas razonables, 4, 25, 43, 60 . . . no 10−10. Si saliera esto ultimo tendrıamos que abrir unosojos como platos de sorpresa. Si usted no sabe esto es porque esta poco familiarizado con losnumeros de Fısica y sus unidades. Hacerlo adecuadamente lleva tiempo aunque parezca quesolo es substituir.

Page 5: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

Table 2:Energy levels Infinite well energy (eV) Finite well energy (eV)

1 1.50523 1.123652 6.02092 4.464673 13.54708 9.913614 24.08370 17.175685 37.63077 24.790906 54.18831 none

19. • [From a book to be uncovered later] Write a computer program to calculate the first ten

roots of tan x = x. Note: If λ1, λ2, . . . are all positive roots of this equation, then∑∞

n=1

1

λ2n

=

tralara− tralara. Check this with Maple.

[Primero calcule lo que es tralara-tralara como hice yo en clase (a mano, como Euler, con suserie). Cuando lo haya calculado y haya encontrado las 10 raıces pedidas podra comprobar sisus numeros cumplen la relacion anterior.]

20. • Solve the system x4 + y4 − 67 = 0, x3 − 3xy2 + 35 = 0 near x = 2., y = 3.. Note: Be carefuland give several input points. The plot here (the magnified plot) is important.

21. • Choose two of the three following algorithms, iterative method, Newton-Raphson, steepestdescent (no tiene usted por que saber los tres si no se han explicado en clase, pero dos sı quesabe usted utilizar) to find a solution of

x = 0.7 sin x+ 0.2 cos y, y = 0.7 cos x− 0.2 sin y

near (0.5, 0.5)

NUMERICAL INTEGRATION OR QUADRATURE

22. [Experimental Mathematics] Simpon formula is exact (not an approximation) if one integratesany cubic polynomial. Check it with the following two examples: i) By hand. Calculate∫ 41 dxx3 with the primitive and with Simpson formula, x1 = 1, x2 = 5/2, x3 = 4. Both results

agree, 633

4. ii) With Maple. Calculate

∫ 7

log 2dx 5 + ζ(5)x2 + 15x3,

with the same two methods, now x1 = log 2, x3 = 7 and x2 the middle point of the previoustwo.

Result: 35− 5 log 2 +343

3ζ(5)−

1

3ζ(5)(log 2)3. La constante ζ(5) es la Zeta de Riemann en el

5.

23. • With the express straightforward method explained in the lectures (invented term, if you cansay ‘metodo de Newton-Raspon’ I can say this too) derive the five-point Newton-Cotes formula(known as Bode’s rule but this is a typo as some authors point and should be called Boole’srule instead), that again benefits from a cancellation.

Calculate the explicit numerical coefficient of the error with the same method. Checkyour answer (not copy from!) with, for example, http://mathworld.wolfram.com/Newton-CotesFormulas.html

Page 6: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

24. [Ex Feb2012] a) Determinar las constantes a, b, c tal que la regla de cuadratura

∫ 1

−1f(x) dx ≈ af(−1) + af(1) + bf(−c) + bf(c)

sea exacta para polinomios del mayor grado posible. Diga claramente cual es el grado maximo.

b) Usar la regla para aproximar la siguiente integral (con a, b, c los valores calculados en a),por supuesto)

∫ 4

0e√x dx.

¿Sabrıa usted calcular a mano el valor exacto? (esto ya no se pedıa en el examen, pero salefacilmente. Si lo sabe, bien).

Solucion a a): The precision of the rule is 5 (se llama ası, precision, vale hasta orden 5, para6 ya no. De haber escrito un error con derivadas en la regla –que para cuadraturas de Gaussno he explicado ni pido– el error irıa con una derivada sexta evaluada en algun punto delintervalo considerado porque la derivada sexta de un polinomio de orden 5 es cero.)

25. • Sabiendo que la formula de cuadratura gaussiana a 3-puntos dada por

∫ 1

−1f(x) dx ≈

5

9f

(

−√

3

5

)

+8

9f(0) +

5

9f

(

3

5

)

es exacta para polinomios de hasta quinto orden, cinco incluido, calcule, como hice yo en

clase, el error. Si su calculo es correcto habra obtenido lo que predice la formula del libroNumerical Methods and Software by Kahaner, D et al,

(b− a)2n+1(n!)4

(2n+ 1)[(2n)!]3f (2n)(ξ),

NUMEROS PSEUDO-ALEATORIOS

26. Usando unas tablas de numeros aleatorios sortear 10 variables (claramente en problemas deverdad se preparan muchas mas, 10 es solo para el ejemplo) con la distribucion:

(

3 40.58 0.42

)

.

27. Here are 4-digit numbers generated with the middle square method proposed by J. von Neu-mann in the 1940’s. The starting point has been 3567. Observe that the sequence enters in acycle very soon.

3567, 7234, 3307, 9362, 6470, 8609, 1148, 3179, 1060, 1236, 5276, 8361, 9063, 1379, 9016, 2882,3059, 3574, 7734, 8147, 3736, 9576, 6997, 9580, 7764, 2796, 8176, 8469, 7239, 4031, 2489, 1951,8064, 280, 784, 6146, 7733, 7992, 8720, 384, 1474, 1726, 9790, 8441, 2504, 2700, 2900, 4100,8100, 6100, 2100, 4100

28. • [Knuth, pag 7] A mano. What number follows 1010101010 in the middle square method?Sol: 3040504030.

29. Determine all primitive roots for p = 11. Sol: 2, 6, 7, 8

Page 7: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

30. • [Examen Feb2012] (Con calculadora o a mano, de ambas maneras sale) Sea el generador decongruencias lineales

xi+1 = 29xi mod 32.

a) Utilizando un teorema visto en clase determinar si tiene perıodo maximo. b) Tomandocomo semilla 7, ¿cual es el perıodo? ¿Y tomando como semilla 15? ¿Y tomando un 4? ¿Ysi la semilla es 6? A la vista de lo obtenido en estas preguntas, ¿depende el perıodo de estegenerador de que la semilla elegida sea par o impar? c) Con el resultado de los apartados a) y b),¿podrıa enunciar una regla general acerca del perıodo maximo de generadores multiplicativoscon modulo m = 2k?

Sol: a) No. 32 is not prime. Besides 29 is not a primitive root of 32 b) 8. 8. 2. 4. Sı, depende.c) The conclusion is that the maximum period is m/4

31. • i) Determine 24n mod 31 for n = 1, . . . 30. Find the smallest n for which the mod operation’sresult is 1. Is 24 a primitive root of 31?

ii) Compute the period of the following generator: xn = 13xn−1 mod 2311

32. Consider the lcg with (a, c,m) = (21, 3, 100). By Theorem 1 it has full period 100. Plotting allpoints of the form (xi, xi+1) in a 2D picture check for serial correlations. (We will discover thatall points line on 9 parallel lines with slope 1, and also will identify other lines of slope −4).

6, 29, 12, 55, 58, 21, 44, 27, 70, 73, 36, 59, 42, 85, 88, 51, 74, 57, 0, 3, 66, 89, 72, 15, 18, 81, 4,87, 30, 33, 96, 19, 2, 45, 48, 11, 34, 17, 60, 63, 26, 49, 32, 75, 78, 41, 64, 47, 90, 93, 56, 79, 62,5, 8, 71, 94, 77, 20, 23, 86, 9, 92, 35, 38, 1, 24, 7, 50, 53, 16, 39, 22, 65, 68, 31, 54, 37, 80, 83,46, 69, 52, 95, 98, 61, 84, 67, 10, 13, 76, 99, 82, 25, 28, 91, 14, 97, 40, 43, 6, 29, 12

33. The RANDU generator was widely used on IBM 360/370 machines. Defined by the choice(a, c,m) = (216+3, 0, 231), it had very bad random properties. While the results from RANDUplotted in a 1D distribution looked okay, and still looked okay in a 2D distribution, in a 3Dhad serious problem when observed at the right angle!

34. Generators of pseudo-random numbers that you can use safely:

a) The Minimal Standard lcg defined by the choice (a, c,m) = (75, 0, 231 − 1). The number231 − 1 = 2147483647 is a Mersenne prime

b) The lcgmethod used in Maple<Maple 10 mathematical software (a, c,m) = (427419669081, 0, 1012−11). Observe that 1012 − 11 = 999999999989 is the largest prime number of twelve digits.

Both a) and b) give quite satisfactory results as generatos of random numbers, though theirperiods are short.

Ambos los puede usar para los calculos que vamos a hacer en clase. De ninguna manera puede utilizar usted

un generador inferior al Minimal Standard. Si elige usted otro generador, dıgame, por favor, la referencia de

donde lo ha tomado y los test que ha pasado. Inventados no valen. Si no me va a dar esa informacion, use uno

de estos dos. O los nuevos de ahora de Maple (Mersenne Twister) que segun dice ‘help’ son magnıficos

Page 8: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

35. • Con Maple. Sea la siguiente secuencia de Fibonacci,

xn+1 = (xn + xn−1) mod m.

Calcular: (i) el perıodo de la secuencia cuando m = 10. El perıodo no depende (aquıi) de lasemilla elegida, ya lo sabeis, pero para que vuestros x1, x2, . . . coincidan con los mıos tomadcomo semilla x−1 = 1 y x0 = 4. Ası pues aseguraos de que x22 = 9 y x27 = 2. (ii) Con laeleccion de la semilla indicada en (i), ¿Cuanto son x100, x276 y x340? (iii) Si se disponen lospuntos generados en un espacio tridimensional, se observan dos planos (solo dos). Encontrarlas ecuaciones de dichos planos. Nota: Este generador, con otros m’s por supuesto, fue con-siderado al principio de los anos 1950s y habitualmente tiene un perıodo superior a m.

36. • [Para hacer en el lab conmigo]. Con Maple. He generado varios numeros aleatorios con ungenerador de congruencias lineales mixto, o sea, de la forma

xn = (axn−1 + c) mod m,

pero en un descuido he borrado el programa y ahora no se cuales eran los parametros a, c,m delgenerador. Afortunadamente recuerdo que los primeros numeros obtenidos eran: 1486584891,2502414592, 3645611265, 2122211086, 245917623, 4173278796 y 1402184157. Con estos datos(creo que incluso sobran) calcular a, c y m.

Nota: Esta es la razon por la que el metodo de congruencias lineales no se emplea en encriptacion: porque se

adivina la clave a, c y m facilmente.

METODO DE MONTE CARLO

37. Usando tecnicas de Monte Carlo evaluar el numero π mediante la integral∫ ∫

σdxdy, donde σ

es el cırculo de radio unidad, o sea x2 + y2 ≤ 1. Para calcular esta integral encerrar el cırculoen un cuadrado de lado 2 y generar una secuencia uniforme de numeros pseudo-aleatorios(xi, yi), i = 1, . . . N en [−1, 1]. El valor de π vendra dado por 4n/N , siendo n el numero depuntos que han caido dentro del cırculo. Incrementar N hasta conseguir π con tres cifrassignificativas (lo cual no es mucho pedir!). Escribir los errores.

Las tecnicas de Monte Carlo no se usan para calcular aproximaciones de π porque desde los tiempos de Newton

se conocen metodos analıticos que hacen el trabajo mucho mejor. Por favor, no tome este ejercicio mas que

como un ejemplo ilustrativo que viene en todos los libros de iniciacion a MC. Distinto es el caso de cos x2 que

aparece en muchos problemas de la Optica. No se conoce la integral de esta funcion en terminos de funciones

elementales, ası que para calcular∫√π/2

0dx cos x2 hay que tirar de aproximaciones.

38. [Experimento con ordenador] Para entender el Teorema Central del Lımite de la Teorıa deProbabilidades o que la suma de un numero grande de variables aleatorias independientespreparadas de la misma forma se aproxima muy exactamente a una distribucion gaussiana, hagael siguiente experimento con Maple: 1) Genere N = 1000 variables distribuidas uniformementeente 0 y 1 con un buen metodo de congruencias lineales. 2) Sume las 10 primeras variables yguarde el resultado, sume las siguientes 10 y guarde, ası hasta el final. 3) Pinte estas nuevasvariables (llamemoslas y) en un histograma como hicimos en clase. La forma del histogramaya no es la que corresponde a una distribucion uniforme (recuerde que esta es casi horizontal,con todas las barras de altura parecida), ahora tiene otro perfil, ¿lo ve? 4) Como Maple puedesuperponer dibujos con display ponga juntos en el mismo frame el anterior histograma y eldibujo de una distribucion normal de media 5 y de desviacion standard

5/6. Son exactos!(bueno, casi). 5) Comentario: recuerde que no hace falta que las variables originales seanuniformes. Usted podrıa haberlo hecho el experimento con variables entre 0 y 1, por ejemplo,

Page 9: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

preparadas con una densidad de probabilidad p(x) = p+2qx+3rx2 (p, q, r constantes positivastal que p+ q+ r = 1) y tambien habrıa salido una Gaussiana pero de media a y de desviacionstandard σ. • Calcule a y σ con Maple o a mano.

Por el mismo precio uno puede preguntarse ¿sera tambien una distribucion gaussiana el producto de dos variables

uniformes entre 0 y 1? Pruebe a ver que sale dibujando el histograma. Desde luego no es una gaussiana. En

este caso creo que el histograma se aproxima muy bien por la densidad de probabilidad − log x.

Para terminar, de la referencia de Glen, Leemis, y Drew, Computing the Distribution of the Product of Two

Continuous Random Variables, en Computational Statistics and Data Analysis, 44 (2004) 451-464, he copiado

lo siguiente: el producto de dos distribuciones uniformes, una entre 1 y 2 y la otra ente 3 y 4 tiene como

densidad de probabilidad log x− log 3 si x (x denota el producto) esta entre 3 y 4, log 4− log 3 si esta entre 4 y

6 y 3 log 2 − log x si esta entre 6 y 8. Ver que esto es ası dibujando el histograma en el mismo frame que esta

distribucion (no hay que calcular nada, solo dibujar y superponer dibujos con Maple). Exactos!

39. Con Maple. Seleccione dos puntos aleatorios sobre la circunferencia unidad. ¿Donde es deesperar que caiga el centro de gravedad de esos dos puntos? Haga lo mismo con tres y cuatropuntos tirados al azar.

Ayuda: Si considera dos puntos las coordenadas del c.d.g. seran

x = (cos θ1 + cos θ2)/2, y = (sin θ1 + sin θ2)/2,

siendo la coordenada radial r =√

x2 + y2. No hace falta decir que la coordenada angular estarauniformemente distribuida pues cualquier posicion angular sera tan probable como cualquierotra. Vamos con la coordenada radial que es mas interesante. Para ver como se distribuyeesta tire los dos puntos sobre la circunferencia unidad (lo puede hacer con numeros aleatoriosdistribuidos uniformemente ente 0 y 2π y luego les calcula el seno y el coseno). Calcule r. Pinteun histograma con la distribucion de r. La forma del histograma sera p(r): la densidad deprobabilidad de que al medir el cdg se obtenga un valor entre r y r+dr. Se atreve a aproximarp(r) analıticamente (aunque sea a ojo)? (yo se calcular p(r) exactactamente en este caso, esfacil, pero si se trata de tres, cuatro puntos ya la cosa cambia... saco histograma, algun valormedio (exacto) y poco mas).

40. [Generating numbers that fit a given probability density] Use a uniformly distributed randomvariable in [0, 1) to obtain N = 1000 real numbers u from −∞ to ∞ with the probabilitydensity

p(u) =1

2 cosh π u2

,

and answer the following questions:

i) The numbers are mainly concentrated in a finite interval [−a, a] around u = 0. Find anumerical estimate of a.

ii) Calculate the mean value of1

u2 + 1. Could be this value an estimate of log 2?

This is part of a result obtained by Hulthen in 1938 corcerning the ground state of an antiferromagnetic s = 1/2

XXX-Heisenberg spin chain. Yo solo lo he reformulado en terminos de variables aleatorias para convertirlo en

un ejercicio academico.

Page 10: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

PARA ENTREGAR CUANDO YO LOS PIDA (pedidos el 1 de Febrero de 2012)

41. • Con Maple. Sea Ω la region solida limitada superiormente por el cilindro parabolico z = 4−y2

e inferiormente por el paraboloide elıptico z = x2 +3y2. ¿Puede pintar Ω con Maple? Calculeel volumen de Ω. Hagalo de dos maneras: analıticamente -si sabe- o en su defecto pidiendoseloa Maple, y por el metodo de Monte Carlo (utilice un generador de numeros aleatorios bueno,el que usted quiera pero bueno). En este ultimo caso tire N = 100, 1000 y 10000 puntos. ¿ConN = 10000 se obtienen tres cifras significativas del volumen pedido? Haga calculo de errores.

42. • Con Maple. Calcular por Monte Carlo una aproximacion–con la estimacion del error–alvalor de la integral

∫ 1

0

∫ 1

0

∫ 1

0

∫ 1

0

∫ 1

0

∫ 1

0

dx dy dz du dv dw

1 + x+ y + z + u+ v + w

Calcular tambien con Maple su valor exacto.

NOTAS QUE LEO O RECUERDO Y SON INTERESANTES

– The linear congruent method is also known as power residue method. It was proposed byD.H. Lehmer in 1948.

– For multiplicative lcg with modulus m = 2k the maximum possible period is 2k−2 (i.e., m/4).The seed should be odd.

Esto se ve con el ejemplo xi+1 = (29xi) mod 256. El perıodo es 64, y es lo mejor quepodemos obtener porque cambiando 29 por, digamos, 31 la cosa va aun peor: el perıodo sequeda en 8 solamente. Y esto si la semilla es impar. De empezar con una semilla par enxi+1 = (29xi) mod 256, por ejemplo un 4, el perıodo es solo 16.

– Let p be a prime number. Definition: When 2p − 1 is prime it is said to be a Mersenne prime.

It is possible to omit that p is prime. Why? Because 2p − 1 is prime only if p is prime. It is atheorem and it is easy to prove. A non prime number is called a composite number

– What are primitive roots? Let p be a prime. Then b is a primitive root for p if the powers of b,1, b, b2, b3, . . . include all of the residue classes mod p (except 0). Since there are p− 1 residueclasses mod p (not counting 0), that means the the first p− 1 powers of b have to be differentmod p. We have noticed that the powers of b form a repeating cycle, and that cycle cannot belonger than p− 1 (because of Fermat’s Little Theorem). So, b is a primitive root if the cycle isas long as it can possibly be.

Example: If p = 7, then 3 is a primitive root for p because the powers of 3 are 1, 3, 2, 6, 4, 5–thatis, every number mod 7 occurs except 0. But 2 is not a primitive root because the powers of2 are 1, 2, 4, 1, 2, 4, 1, 2, 4 . . . missing several values.

Another example: If p = 13, then 2 is a primitive root because the powers of 2 are1, 2, 4, 8, 3, 6, 12, 11, 9, 5, 10, 7–which is all of the classes mod 13 except 0. There are otherprimitive roots for 13.

Theorem: If p is a prime, then there is a primitive root for p. (In fact, if p is a prime andp > 2, there are always at least two primitive roots, and sometimes many more.)

How to find a primitive root for p? Just try possibilities, starting with 2, 3, . . ., until you findone that works.

Page 11: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

– Maple tambien calcula raıces primitivas. Package: with(numtheory), comands ‘order’ or ‘prim-root’ –lo que no exime, en este curso, de hacerlas a mano cuando se pueda, ni de emplear unprograma Maple sencillo hecho por cada uno de nosotros cuando no se pueda a mano.

– La probabilidad de que dos enteros m y n tomados al azar sean relativamente primos (tambiense dice coprimos y se escribe (m,n) = 1) es

P ((m,n) = 1) =1

ζ(2)=

6

π2= 0.607927 . . . ,

donde ζ es la funcion Zeta de Riemann.

– George Marsaglia wrote the paper ”Random numbers fall mainly in the planes”, Natl. Acad.Sci. Prec. 61 (1968), 25-28. The paper shows a defect inherent in all linear congruentialmethods used to generate random numbers. It assumes a strong familiarity with AbstractAlgebra and Linear Algebra.

An excellent test of random sequences is DIEHARD, maintained by George Marsaglia inhttp://stat.fsu.edu/∼geo The page has both executables and source code.

– Chi-square distribution, Chi-square test... (it reads ”kai-square”). Los matematicos espanolespuede que digan ji-escuer, pero no lo se porque solo se lo he oıdo a uno.

– Normal deviates: Random numbers with the normal distribution.

– El Teorema Fundamental del Algebra lo demostro Gauss en 1799.

– ‘One must always invert’, Carl G. J. Jacobi, 1804-1851.

– “Toda labor de investigacion para ser fecunda, exige una jornada mınima de ocho horas”, JulioRey Pastor, 1888-1962.

– Richardson interpolation is described in the book of Press et al. as a process to turn lead intogold. Tela marinera!

– Mecanica Cuantica: En los calculos analıticos de los coeficientes de reflexion y transmision deuna barrera, siempre se calcula el de trasmision. Simplemente porque es mas facil de calcular.Por eso es el que tabulan los libros.

Page 12: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

#####################################################

####### April 2012

######################################################

Metodo de Newton para resolver f(x)=0 Input (o lo que usted debe dar al programa): f(x), fp(x), x0, numero de iteraciones N (aqui no lo he llamdo N, he puesto 10 directamente), tolerance (aqui 10^(-6), puede usted cambiarlo).

Comentarios: 1-Hay casi un cero de f(x) en [-3,-2], pero si uno se acerca se ve que es mentira, no lo hay. Se ve con plot.2-Yo he calculado fp(x), la derivada de f(x), con diff(f(x),x); y luego definido esta copiando con el raton.3- El punto inicial x0=-100. es una mala eleccion, pero converge lo mismo... al cabo de muchas iteraciones (26), convergencia no cuadratica, pero convergencia al fin y al cabo. Y si se empieza porx0=5+I*1.5 (quien dice que no se pueden usar complejos?? Se usan igual, faltaria mas) tarda 7 iteraciones.

restart: with(plots):

f:=x->x^3+4*x^2-10: fp:=x->3*x^2+8*x: plot(f(x),x=-4..2); x0:=evalf(5+I*1.5): #good choice: 4 iterations #x0:=evalf(-1.5): #bad choice: 61 iterations. Worse than -100 diff(f(x),x);

n:='n':for n from 1 to 10 dox1:=x0-f(x0)/fp(x0): if abs(x1-x0)<10^(-6) then break else x0:=x1end if;end do;n;

x0 1 2

5

10

Page 13: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(1)(1)7

##############################################################################

Newton compared with secant to solve f(x)=0 Same exercise with Newton and Secant methods

######## Newtonrestart:f:=x->x^3+4*x^2-10:diff(f(x),x);fp:=x->3*x^2+8*x:x0:=evalf(1): #good choice of the starting point

n:='n':for n from 1 to 15 dox1:=x0-f(x0)/fp(x0): if abs(x1-x0)<10^(-6) then break else x0:=x1end if;end do;n;

##### Secantx0:=1: x1:=2:n:='n': for n from 1 to 10 dox2:=evalf(x1-f(x1)*(x1-x0)/(f(x1)-f(x0))): #f(x2);if (abs(x2-x1))<10^(-6) then break else x0:=x1: x1:=x2: end if: end do;n;

Page 14: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(4)(4)

(2)(2)

(3)(3)

5

6

Digits:=20: fsolve(f(x),x); ### Lo que dice Maple1.3652300134140968458

###############################################################################

Un metodo iterativo. Este no converge. Input: F(x), (no hace falta derivada), x0, numero de iteraciones (7), y tolerancia (10^(-6))

restart:F:=x->x^3+4*x^2+x-10; x0:=1.5:n:='n': for n from 1 to 7 dox1:=F(x0):if abs(x1-x0)<10^(-6) then break else x0:=x1end if: end do;n;

8

###############################################################################

Tres+dos dibujos en el mismo frame. Cinco en total. Las rectas negras quedan a 45 grados con la horizontal. Se cortan en la solucion F1(x)=F3(x)=F5(x)=0.

Si se estudia desde el punto de vista de tres esquemas iterativos F1(x)=x, F3(x)=x,F5(x)=x, se tiene que: rojo diverge, azul converge... lentamente pero converge yverde converge rapido (claro, es Newton, la estrella)

Page 15: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

restart:F1:=x->x^3+4*x^2+x-10; F3:=x->sqrt(10-x^3)/2:F5:=x->x-(x^3+4*x^2-10)/(3*x^2+8*x);

plot([F1(x),F3(x),F5(x),x,1.365230013-(x-1.365230013)],x=-4.5..3.1,y=-3..4,discont=true,color=[red,blue,green,black,black]);

x0 1 2 3

y

1

2

3

4

#################################################################

Newton en dos (o mas) dimensiones. Esto ya es otra cosa... aqui ya llegan pocos packages. Los hay, pero siempre resuelven otro problema distinto al que uno tiene. La ultima sentencia es un teorema (es broma).

Input: f1,f2; matriz Jacobiana, su inversa, x0, y0, numero de iteraciones (15) tolerancia (10^(-9)):Eso quiere decir que del resultado final solo podemos decir que POR LO MENOS 9 cifras decimales son exactas. Ojo que es un Newton y va que vuela. Si tarda 15, 20 iteraciones... es que algo pasa.Es tarea nuestra saber el que.

Si el input es complejo x0:=0.9+11*I: y0:=0.7: le cuesta 26 iteraciones. Se cambiua15 por 50 y encima sobran.

Page 16: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(5)(5)

restart: with(plots): with(LinearAlgebra): with(VectorCalculus):f1:=(x,y)->sin(x+y)-x:f2:=(x,y)->cos(x-y)-y:

##### Maple sabe resolverlo el solitofsolve(f1,f2);### o tb fsolve(f1(x,y),f2(x,y));

##### Este lo sabe resolver maple (hay solo una solucion y te la da).### Como hubiera mas de una solucion ibamos listos para darnos Maple #### la que nosotros buscamos... tendriamos que ir diciendo, avoid tal solution #### avoid also that solution....

implicitplot([x=sin(x+y),y=cos(x-y)],x=-2..2,y=-1.5..1.5,color=[red,blue]);

x0 1 2

y1

##################################### Para ver que funciona### El jacobiano (una matriz)Jacobian([f1(x,y),f2(x,y)],[x,y]);#### En el punto (2,5) y la llamo J. Su inversa en ese punto J:=Jacobian([f1(x,y),f2(x,y)],[x,y]=[2.,5.]); Jinverse:=MatrixInverse(J);

Page 17: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(6)(6)

x0:=0.9+0*I: y0:=0.7: n:='n':for n from 1 to 15 do J:=Jacobian([f1(x,y),f2(x,y)],[x,y]=[x0,y0]); Jinverse:=MatrixInverse(J);v:=Vector(1..2,[x0, y0])-Jinverse.Vector(1..2, [f1(x0,y0),f2(x0,y0)]); if (abs(v[1]-x0)<10^(-9)) and (abs(v[2]-y0)<10^(-9)) then breakelsex0:=v[1]: y0:=v[2]:end if: end do; n;

Page 18: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(9)(9)

(8)(8)

(7)(7)5

###############################################################################

Generando numeros aleatorios con el antiguo lcg method que tenia Maple en las tripasInput: N, x[1]. a, m fijados por los libros. Si se necesitanm entre [o,1) hay que dividir cada x[n] por m

restart: with(Statistics): #### antigua (Maple9 o inferior). ### with(plots):N:=100: a:=427419669081: m:=10^12-11: x[1]:=9574396327:for i from 2 to N dox[i]:=irem(a*x[i-1],m): #### generador de numeros aleatorios: lo tiene Maple somewhereend do:seq(x[i],i=1..10);

i:='i': sum(x[i],i=1..60);

i:='i': sum((x[i])^2,i=1..N)/N; evalf(%);28171801079590

687997083603351195878818925

###############################################################################

Page 19: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(10)(10)

(11)(11)

Generando numeros aleatorios con el nuevo generador de Maple en with(RandomTools[MersenneTwister]): Input: N. los numeros estan entre [0,1) uniformemente distribuidos.

restart: with(RandomTools[MersenneTwister]):N:=1000: for i from 1 to N dox[i]:=GenerateFloat();end do:seq(x[i],i=1..15);

Esto dice Help de el. Me parece muy bien. Sin inconveniente en usarlo

The RandomTools[MersenneTwister] subpackage contains functions for creating pseudo-random number generators using the Mersenne Twister algorithm. This algorithm has the following properties: -- the command outputs a pseudo-random float uniformly distributed in [0,1), -- period length of 2^19937-1-- 623-dimensional equidistribution property-- passed various tests, including the diehard test by G. Marsaglia and the load test by O.Hellekalek and S. Wegenkittl-- very fast

###############################################################################

Input: N. Los numeros son enteros entre [0, ) uniformemente distribuidos.

restart: N:=1000: with(RandomTools[MersenneTwister]):

for i from 1 to N dox[i]:=GenerateInteger();end do:seq(x[i],i=1..15);

#############################################################################33

#############################################################################

Page 20: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(12)(12)

### Number 5. RANDU

### Oct 13th 2011restart:with(Statistics): with(plots):2^31: N:=5000: m:=2^31: N/30.;x:=array(1..N):x[1]:=314156:n:='n':for n from 1 to N-1 dox[n+1]:=irem((2^16+3)*x[n],2^31):end do:l:=[seq(evalf(x[i]/m),i=1..N)]:

166.6666666

Histogram(l,color=cyan,frequencyscale=absolute );#### si no se pone frequencyscale=absolute te lo acopla a un area 1

00

20

40

60

80

100

120

140

160

180

i:='i':points:=seq([x[i],x[i+1]],i=1..N-10):pointplot(points,color=black);

Page 21: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

00

i:='i': points:=seq([x[i],x[i+1],x[i+2]],i=1..N-10):pointplot3d(points,color=blue);

393225*1+65539*(-6)+C=0: isolve(%);

############################################################################################# Oct 2011#### Number 8 Calculate Pi with Monte Carlo method

restart:a:=427419669081: m:=10^12-11: N:=100:u[1]:=2718281828: v[1]:=314159261:

Page 22: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(13)(13)

(15)(15)

(14)(14)

(16)(16)

i:='i':for i from 1 to N-1 dou[i+1]:=irem(a*u[i],m): v[i+1]:=irem(a*v[i],m):end do:

i:='i': lu:=seq(u[i],i=1..N): lv:=seq(v[i],i=1..N):

i:='i': for i from 1 to N do x[i]:=-1.+2.*evalf(u[i]/m):y[i]:=-1.+2.*evalf(v[i]/m):end do:seq(x[i],i=1..N):

i:='i': for i from 1 to N doif (x[i]^2+y[i]^2<=1.0) then f[i]:=1 else f[i]:=0end if: end do:seq(f[i],i=1..N):

i:='i':n:=sum(f[i],i=1..N);Vbox:=4: #### Abox en realidad, no importa Pi_approx:=evalf(Vbox*n/N);

#### Alternativa (MEJOR QUE LO ANTERIOR AQUI: no se le fuerza aMaple a recordar tanto numero)n:=0: for j from 1 to N doif (x[j]^2+y[j]^2<=1.0) then n:=n+1 end if: end do:n;Pi_approx:=evalf(Vbox*n/N);

69

#### error as in Numerical Recipes (Press-Teukolsky book)error_estimate:=evalf(Vbox*sqrt(n*(N-n)/N^3));

[Pi_approx-error_estimate,Pi_approx+error_estimate]; #con prob del 68%[Pi_approx-2*error_estimate,Pi_approx+2*error_estimate]; #95%[Pi_approx-3*error_estimate,Pi_approx+3*error_estimate]; #99.730020% Lease: es casi imposible...

Page 23: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(20)(20)

(17)(17)

(19)(19)

(18)(18)

##### De donde salen esas probabilidades...p:=x->exp(-(x-mu)^2/(2*sigma^2))/sigma/sqrt(2*Pi):int(p(x),x=mu-3*sigma..mu+3*sigma); evalf(%);

0.9973002039

###### Observe that valor_medio_de_las_f:=sum(f[i],i=1..N)/N; #### o sea n/Nvalor_medio_de_las_fsquare:=sum((f[i])^2,i=1..N)/N; #### o sea n/N

(valor_medio_de_las_fsquare-( valor_medio_de_las_f)^2)/N: Vbox*sqrt(%): err:=evalf(%);##### Coincide con error_estimate: claro, es lo mismo.

##################################################################################3

############################################################################################# Computer test: the sum of indep random variables prepared with no matter

##### what distribution ##### is normal (if the number of terms in the sum is large). ##### Here the number of terms ##### is 10 and the starting variables are uniformly distributed in [0,1)##### Students; have to know how to get the Histogram (pink) (or they have to ##### construct one). The blue curve is maths, not random variables....###############################

restart: with(Statistics): with(plots):N:=100: #### modifiquese a voluntad: el dibujo saldra mejora:=427419669081: m:=10^(12)-11: x[1]:=9574396327:for i from 2 to N dox[i]:=irem(a*x[i-1],m): #### generador de numeros alotorios: lotenia Maple somewhereend do:

seq(x[i],i=1..20);

Page 24: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered

(21)(21)

i:='i': sum(x[i],i=1..10);i:='i': sum(x[i],i=11..20);i:='i': sum(x[i],i=21..30);

3693138066594

5045283411549

4088851178890

##### Del input anterior...i:='i': j:='j':for j from 1 to N/10 do y[j]:=sum(x[i]/m,i=10*j-9..10*j);end do:

i:='i':l:=[seq(evalf(y[i]),i=1..N/10)]:

#### Gaussian distributiono:=subs(mu=5,sigma=sqrt(5/6),exp(-(x-mu)^2/(2*sigma^2))/(sigma*sqrt(2*Pi)));

##### sin frequencyabsolute (asi la mete en un area igual a 1)p:=Histogram(l,color=pink,title="que cosa mas bien"):q:=plot(o,x=0..10,color=blue):

display(p, q);

x0 2 4 6 8 10

0

1

que cosa mas bien

Page 25: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered
Page 26: UNIVERSIDADCOMPLUTENSEDEMADRID MJRPlaza F´ısica …teorica.fis.ucm.es/ft8/FC12-13.pdf · 14. [Puede utilizar un teorema debido a Cauchy] Find an annulus (corona circular) centered