>
 

M242 Monte Carlo  9/09 

> with(Student[Calculus1]):
 

> f:=x-> 1/(1+x^2);
 

proc (x) options operator, arrow; `/`(1, `*`(`+`(1, `*`(`^`(x, 2))))) end proc (1)
 

> T:= proc(N, a, b)
local h, k, s, exva;
h:= (b-a)/N:
s:= 2*sum(f(a+k*h), k=1..N-1):
exva:= int( f(x), x=a..b):
print( exva,  evalf([exva, (f(a) + s + f(b))*h/2]));
end:
 

> T(100,0,1);
 

`+`(`*`(`/`(1, 4), `*`(Pi))), [.7853981635, .7853939967] (2)
 

> ApproximateInt(f(x), x=0..1, method = trapezoid, partition=10); m:=evalf(%);
 

 

`/`(12248312522521419, 15603313665089800)
.7849814972 (3)
 

Practice Problems Today: 

 

a) Try the case when  f(x) = 1/x  with the interval = [1,2]. 

 

b) Simpson's rule that we'll work on next lecture goes like this: 

 

The interval is broken up into 2n (even) equal subsintervals. The weights distributed on the points 

a= x[0], x[1], x[2], x[3], x[4], ... x[2n-1], x[2n] are respectively 1, 4, 2, 4, 2, ..., 4, 1. 

 

In other words, the odd-indexed x-values are assigned weights 4, all the 'interior' even indexed x-values are assigned 2. The left and right end points are given weight = 1. 

 

Simpson's Rule is: h:= (b-a)/(2*n), S:= (f(a) + 4*f(x1) + 2*f(x2) + 4*f(x3) + ... + 4*f(x_[n-1]) + f(b))*h/3. 

 

Edit the procedure above, sum up the interior y-values by separating the indices into odd and even ones. Finally add them together with f(a) and f(b) as shown above. 

 

Run the new proc on f(x) = 1/x to see if your answer agrees the one below. 

 

> ApproximateInt(f(x), x=0..1, method = simpson, partition=10); m:=evalf(%);
 

 

`/`(5988585315838311774901484536676836463, 7624903642650463520301694141655283000)
.7853981632 (4)
 

Ignore the Monte-Carlo Method below. We do it next time. 

> r:= rand(0..200)/200:
 

> r();
 

`/`(23, 50) (5)
 

> f:=x-> 1/(1+x^2);
 

proc (x) options operator, arrow; `/`(1, `*`(`+`(1, `*`(`^`(x, 2))))) end proc (6)
 

> N:=1000:
 

> for k from 1 to N do xx:= evalf(r()); s[k]:= f(xx); od:
 

> k:='k': sum(s[k],k=1..N)/N;
 

.7842627708 (7)
 

> int(f(x),x=0..1); evalf(%);
 

 

`+`(`*`(`/`(1, 4), `*`(Pi)))
.7853981635 (8)
 

Two-dimensional Monte-Carlo. 

Let's try to find the area of an ellipse defined by (x/a)^2 + (y/b)^2 = 1. 

> aa:=0.8: bb:= 0.4:
 

> with(plots):
 

> implicitplot( (x/aa)^2 + (y/bb)^2 = 1, x=-3..3, y=-2..2, grid=[30,30], scaling=constrained, axes=boxed);
 

Plot_2d
 

Introduction to 'conditional if' . 

> N:=5000:
 

> k:= 'k': con:= 0:
for k from 1 to N do xx:=r(); yy:=r(); if xx^2/aa^2+yy^2/bb^2 < 1
then con:= con + 1; else con:= con + 0; end if; od:
 

> evalf(con/N);
 

.2558000000 (9)
 

> int(bb*sqrt( 1 - (x/aa)^2), x=0..aa); #exact area of a quarter of an ellipse.
 

.2513274123 (10)
 

>