CS 100: Lecture L19
April 6
Example 1.
% Script File L1
t = linspace(0,3); s = sin(2*pi*t); plot(t,s) title('The Sine Function')
Example 2
%Script File L2
nmax = 200; x = zeros(1,nmax); x(1) = input('Enter the starting value:'); k = 1; while (x(k)~=1 & k<=nmax) if rem(x(k),2)==0 x(k+1) = x(k)/2; else x(k+1) = 3*x(k)+1; end k=k+1; end plot(x(1:k))
Example 3.
% Script File: L3 tic hits = 0; nMax = 100000; for k=1:nMax x = -1+2*rand(1,1); y = -1+2*rand(1,1); if x^2 + y^2 <= 1 hits = hits+1; end end appxPi = (hits/nMax)*4 toc
Example 4.
% Script File: L4 tic hits = 0; nMax = 100; for k=1:nMax x = -1+2*rand(1000,1); y = -1+2*rand(1000,1); hits = hits + sum(x.^2 + y.^2 <= 1); end appxPi = (hits/(nMax*1000))*4 toc