Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a sequence of sentences that use the random generator command rand to dete

ID: 3542774 • Letter: W

Question

Write a sequence of sentences that use the random generator command rand to determine:

(a) The number of random numbers it takes to add up to 20 (or more).

(b) The number of random numbers it takes before a number between 0.8 and 0.85

(c) The number of random numbers it takes before the mean of those numbers is within 0.01 and 0.5

Explanation / Answer

These code snippets do the job but their repeated use is much more interesting. An example is given for the first exercise. a. total = 0; % initialize current sum (the test variable) count = 0; % initialize the counter (output of the program) while total < 20 % loop until 20 is exceeded count = count + 1; % another loop repeat => another number added x = rand(1,1); total = total + x; % modify the test variable! end disp(['It took ',int2str(count),' numbers this time.']) ------------------------------------------------------------ To do this many times, place the above code in a for-loop. Some simple (though perhaps subtle) changes are needed wth respect to retaining the counts for each repeat. Also, the summary has been changed from a single text message to a histogram. Nrep = 1000; % collect 1000 repeats of the above code count = zeros(Nrep,1); for j = 1:Nrep total = 0; % reset the test variable each repeat!!! while total < 20 count(j) = count(j) + 1; % use a vector to capture each result total = total + rand(1,1); end end hist(count,min(count):max(count)) xlabel('Number of random numbers from U(0,1) added to make 20') ylabel('Count') title(['Histogram of results for ',int2str(Nrep),' repeats']) ------------------------------------------------------------ b. count = 0; while 1 % infinite loop use count = count + 1; x = rand(1,1); % get a number if (x < 0.85) & (x > 0.8) % check the value break % bail out if in selected range end end disp(['It took ',int2str(count),' numbers this time.']) c. count = 0; avg = 0; % test variable while abs(avg - 0.5) > 0.01 count = count + 1; % The following line is one way to update the average. % (count-1)*avg is the sum of the first count-1 numbers % and rand just adds another number. Dividing by count % then gives the new average. avg = ((count-1)*avg + rand(1,1))/count; % modify the test var. % There are other ways to do this and you are encouraged % to come up with them end disp(['It took ',int2str(count),' numbers this time.'])
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote