how to write code for birthday problem in matlab in matlab

The Birthday Problem is a probability problem that asks how many people you need to have in a room so that there is a greater than 50% chance that two people will share a birthday.

Here's the Matlab code to calculate the probability of having at least two people with the same birthday:

main.m
function [prob] = birthdayProblem(n)
% n is the number of people in the room
days = 1:365; % number of days in a year
prob = 1;
for i = 1:n
    prob = prob * (365-i+1)/365;
end
prob = 1 - prob;
end
198 chars
10 lines

To test the code, you can call the function with a number of people as parameter:

main.m
>> birthdayProblem(23)

ans =

    0.5073
42 chars
6 lines

This means that for 23 people in a room, the probability of having at least two people with the same birthday is 50.73%.

related categories

gistlibby LogSnag