% dice simulation and Chi Squared test % DiceSimulation.m % L Braile 1/31/05 n = 120 % number of rolls nd = zeros(1,6); edges = [0:1:6]; for i = 1:n x = rand(1,1)*6; % simulate one roll of a die % note that we used rand for a uniform distribution % sample nd1 = histc(x,edges); % make the number 1, 2, 3... 6 nd = nd + nd1(1:6); % Accumulate number of 1's, 2's, etc. end sumrolls = sum(nd) % check to be sure that all rolls are accounted for in nd bar(nd) % plot histogram xlabel('Die result') ylabel('Number of occurrences in 120 rolls') o = nd; % Observed number of 1's, etc. e = ones(1,6)*(n/6); % Expected number in each bin ChiSq = sum(((o - e).^2)./e) % Calculate Chi-squared statistic for data ChiTest = chi2inv(0.95,5) % Obtain Chi-squared test statistic for 95% confidence % and 5 degrees of freedom. For example, for many trials, the calculated % value should exceed the test value only ~5% of the time by chance.