You are on page 1of 14

Probability and statistics

We will be using several of Maple's probability and statistics functions in Math 115. Most of
these functions are used the same way that standard mathematical functions (like sin, cos, ln
etc.) are used -- you just need to be sure to know what the inputs and outputs of the functions
mean. Some of Maple's statistical functions are in the special "stats" library and are accessed in
a way that is a little different than most of Maple's functions. But all this is illustrated below.
Combinatorial functions:
1. Permutations: there are two special functions for permutations that are useful for counting
problems. Of course, the number of permutations of the elements of a set of n distinct elements
is n!, and the standard factorial notation is used in Maple:
>restart:
>15!;

The two special Maple functions are found in the "combinat" library (and must be "with"ed -they are numbperm and permute:
>with(combinat,numbperm,permute);

The numbperm function tells how many permutations there are of a list, which must be enclosed
in square brackets [ ] -- the list may have duplicate elements:
>numbperm([a,b,c]);

>numbperm([a,a,b]);

It is also possible to ask for the number of different ordered subsets having a specified number
of elements of a list. For example, for the number of different 3-element lists taken from the list
[a,a,b,c], we would say:
>numbperm([a,a,b,c],3);

Next, the permute function acts like the numbperm function, except instead of saying how many
permutations there are, the permute function simply lists them all. For instance:
>permute([a,b,c]);

>permute([a,a,b]);

>permute([a,a,b,c],3);

You get the idea -- these three examples are consistent with the previous three. The most
important thing to remember when using permute and numbperm is that the list being permuted
must be enclosed in square brackets.
2. Combinations: There are two (or three) functions which do the same thing as those above,
except for combinations (unordered lists). They are "binomial" (which is always available),
"numbcomb" and "choose" (the latter two must be "with"ed from the combinat package):
>with(combinat,choose, numbcomb);

First, binomial is used to calculate binomial coefficients -- binomial(n,k) is the number of ways
to choose k things out of n:
>binomial(6,2);

Next, numbcomb does the same thing except the first argument of numbcomb may be a list
(enclosed in square brackets, just like numbperm) instead of a number:
>numbcomb([a,b,c,d,e,f],2);

Finally, choose produces the list of all ways to choose the subsets whose number is reported
by numbcomb:
>choose([a,b,c,d,e,f],2);

STATISTICAL FUNCTIONS:
Two kinds of Maple's statistical functions will be useful in Math 151. They are the functions
that calculate "descriptive statistics" for a set of data -- i.e., numbers like the mean, median,
variance and standard deviation. The other kind of useful functions are those that give values of
probability distributions or their related cumulative distribution functions.
Descriptive statistical functions:
As indicated above, these are the functions that calculate means, medians and such of sets of
data. Although Maple allows you to input the data in a variety of ways, we will use only one of
them. You might find it useful later to explore some of the other descriptive statistical functions
Maple can compute, and the other ways to enter data (or read it in from external files).
The statistical functions, like the combinatorial functions, are stored in libraries and must be
loaded from the disk before they can be used. To get the descriptive statistical functions, one
uses both of the following commands:
>with(stats,describe);

>with(describe);

All of the descriptive statistical functions can do their computations on a data list. This is simply
a list of numbers enclosed in square brackets. The functions for mean, median, variance, and
standard deviation are called "mean", "median", "variance" and "standarddeviation",
respectively.

1. The mean function calculates the mean of a list of numbers -- the list must be enclosed in
square brackets:
>mean([3,6,4.2,7,7,2,3]);

You can also name the list ahead of time (so you can calculate mean and variance without
typing the list twice, for example):
>data:=[3,6,4.2,7,7,2,3];

>mean(data);

2. The variance function has the same syntax as the "mean" function, except it computes the
variance of the list:
>variance([3,6,4.2,7,7,2,3]);

>variance(data);

3. The standard deviation is just the square root of the variance, but there is also the Maple
function "standarddeviation" for this in the "describe" subset of the "stats" package:
>standarddeviation(data);

Now that you see the pattern, you can figure out how to use the Maple function median to
compute the median of a data list.
Statistical Distribution Functions

There is another sub-package of the stats package that deals with probability distributions -- it is
called statevalf, and it must be loaded into computer memory using both of the commands:
>with(stats,statevalf);

>with(statevalf);

The commands within statevalf correspond to the operations one wishes to perform on either
discrete probability distribtions (like the binomial distribution) or continuous probability
distributions (like the normal distribution). The operations are
1. Evaluate the probability density function at a given value for a given random variable.
2. Evaluate the cumulative distribution function at a given value of a random variable (to find
the probability that a random sample will yield a value less than or equal to the given value).
This operation answers questions of the form "What is the probability that a sample from this
distribution will be less than or equal to x?".
3. Evaluate the "inverse cumulative distribution function" of a random variable -- this is like
looking up a probability in the body of the normal distribution table in the back of the book.
This operation answers questions of the form "What value is 95% of the population less than?".
1. DISCRETE DISTRIBUTIONS:
Finite discrete random variables assume only finitely many values, like the sum of what comes
up on two dice, or the number of pennies that come up heads when ten are flipped. Maple
understands three discrete distributions that will be useful in Math 151: "empirical", uniform
and binomial.
The discrete uniform distribution is denoted "discreteuniform[a,b]" in Maple. In this
distribution, a and b are whole numbers, and the distribution assigns equal probabilities to the
integers from a to b (inclusive). For example, the distribution discreteuniform[1..6] assigns the
probability 1/6 to each of the whole numbers from 1 through 6 (it is the distribution of the
outcomes of rolling one of a pair of dice).
An empirical distribution is one that is completely specified by the user's input. For example,
the distribution of the sum of two (fair) dice is given in the Finite Math text. To communicate
this distribution to Maple, the proper notation is:
empirical[op(evalf(0, 1/36, 2/36, 3/36, 4/36, 5/36, 6/36, 5/36, 4/36, 3/36, 2/36, 1/36))]
This indicates that the probability of x=1 is 0, the probability of x=2 is 1/36, the probability of
x=3 is 2/36 and so on up to the probability of x=12 is 1/36. In other words, the twelve numbers
in the list represent the probabilities of rolling a 1, 2, 3,...,12 respectively. For some reason,
"empirical" only works when you use floating point numbers -- it gives error messages when
you try to put in the actual fractions. That's why there is an"op(evalf(...))" in the statement. One

doesn't type this alone as a Maple statement -- we illustrate below how to use it.
Finally, binomial distributions are denoted "binomiald[n,p]" -- this notation has the obvious
meaning. (Notice the "d" in the spelling -- leaving this out will result in a "Requested
distribution does not exist" error message.)
Now we come to the uses of statevalf for each of these distributions. First:
>pf[binomiald[5,0.3]](2);

This indicates that the probability of getting 2 out of 5 successes when the probability of success
on each trial is 0.3 is 0.30870. The "pf" in the statement indicates that what is desired is the
probability that the random variable is exactly equal to the number in parentheses.
As an example, consider the following problem from the Finite Math book: "In a certain
congressional district, it is known that 40 percent of the registered voters classify themselves as
conservatives. If ten registered voters are selected at random from this district, what is the
probability that four of them will be conservatives?"
Since ten voters are chosen, and the probability of choosing a conservative is 0.4, the relevant
distribution is the binomial distribution with n=10 and p=0.4, in Maple this is
binomiald[10,0.4]. We want the probability that four of the choices are conservatives -- so 4
goes in the parentheses. The answer to the problem is obtained via the Maple statement:
>pf[binomiald[10,0.4]](4);

The second way to use statevalf with discrete distributions is to calculate the cumulative
distribution: this is the probability that a random variable is less than or equal to a given value.
To illustrate, another problem from the Finite Math texts asks what is the probability that at
most 8 of a random sample of 20 photocells are defective if it is known that 5% of all cells
produced are defective. The relevant probability distribution is the binomial distribution with
n=20 and p=0.05, and we want the probability that the random variable (number of defectives)
is less than or equal to 8. The answer is obtained via the Maple statement:
>dcdf[binomiald[20,0.05]](8);

Note that to get "less than or equal to" we use "dcdf" (which stands for discrete cumulative
distribution function).
To illustrate the use of an empirical distribution, consider the probability of rolling a number
less than or equal to 6 with a pair of dice. We define:

>dice:=empirical[op(evalf([0,1/36,2/36,3/36,4/36,5/36,6/36,5/36, 4/36,3/36,2/36,1/36]))];

Then the probability of getting 6 or less is:


>dcdf[dice](6);

Probabilidade e estatstica
Estaremos utilizando vrios de Probabilidade e Estatstica funes de bordo em matemtica 115.
A maioria destas funes so utilizadas da mesma forma que as funes matemticas padro
(como sin, cos, ln, etc.) so usados - voc s precisa ser Certifique-se de saber o que as entradas
e sadas das funes dizer. Algumas das funes estatsticas de bordo esto no especial
" estatsticas "biblioteca e so acessados de uma maneira que um pouco diferente do que a
maioria das funes de bordo. Mas tudo isso ilustrado abaixo.
funes combinatrias:
. 1 permutaes : h duas funes especiais para permutaes que so teis para problemas de
contagem. Naturalmente, o nmero de permutaes de os elementos de um conjunto de n
elementos distintos n !, e a notao fatorial padro utilizado em Maple:
>reiniciar:
>15 !;

As duas funes especiais de bordo so encontrados no " combinat biblioteca "(e que deve
ser" com "ed - eles so numbperm e permute :
>com (combinat, numbperm, permute);

O numbperm funo diz quantas permutaes existem de uma lista, que deve ser entre
colchetes [] - a lista pode ter elementos duplicados:
>numbperm ([a, b, c]);

>numbperm ([a, a, b]);

Tambm possvel pedir o nmero de subconjuntos ordenados diferentes que tm um


determinado nmero de elementos de uma lista. Por exemplo, para o nmero de diferentes listas
de 3 elementos retirados da lista [a, a, b, c], que diria:
>numbperm ([a, a, b, c], 3);

Em seguida, a permute funo age como o numbperm funo, exceto em vez de dizer quantas
permutaes existem, a permute funo simplesmente lista todos eles. Por exemplo:
>permute ([a, b, c]);

>permute ([a, a, b]);

>permute ([a, a, b, c], 3);

Voc comea a idia - estes trs exemplos so consistentes com os trs anteriores. A coisa mais
importante a lembrar quando usar permute e numbperm que a lista a ser permutada deve ser
colocado entre colchetes. 2.
Combinaes : Existem dois (ou trs) funes que fazem a mesma coisa que aqueles acima,
com exceo de combinaes (no ordenadas listas). Eles so " binomial "(que est sempre
disponvel)," numbcomb "e" escolher "(os dois ltimos devem ser" com "ed
da combinat pacote):
>com (combinat, escolha, numbcomb);

Primeiro, binomial usado para calcular os coeficientes binomiais - binomial (n, k) o nmero
de maneiras de escolher k as coisas de n:
>binomial (6,2);

Em seguida, numbcomb faz a mesma coisa, exceto o primeiro argumento de numbcomb pode
ser uma lista (entre colchetes, assim como numbperm ) em vez de um nmero:
>numbcomb ([a, b, c, d, e, f], 2);

Finalmente, escolher produz a lista de todas as formas para escolher os subconjuntos, cujo
nmero relatado por numbcomb :
>escolher ([a, b, c, d, e, f], 2);

Funes estatsticas : Dois tipos de funes estatsticas de bordo ser til em matemtica 151.
Eles so as funes que calculam "estatstica descritiva" para um conjunto de dados - ou seja,
nmeros como a mdia, mediana, varincia e desvio padro. O outro tipo de funes teis so
aqueles que apresentam valores de distribuies de probabilidade ou as suas funes de
distribuio cumulativas relacionadas.

funes estatsticas descritivas : Como indicado acima, essas so as funes que calculam
mdias, medianas e tal de conjuntos de dados. Apesar de bordo permite a entrada de dados em
uma variedade de maneiras, vamos usar apenas um deles. Voc pode achar que til mais tarde
para explorar algumas das outras funes de estatstica descritiva de bordo podem calcular, e as
outras formas de inserir dados (ou l-lo a partir de arquivos externos). As funes estatsticas,
como as funes combinatrias, so armazenados em bibliotecas e deve ser carregado a partir
do disco antes que eles possam ser utilizados. Para obter as funes de estatstica descritiva,
utiliza-se tanto dos seguintes comandos:

>(com estatsticas, descrever);

>com (descrever);

Todas as funes de estatstica descritiva pode fazer seus clculos em uma lista de dados. Isto
simplesmente uma lista de nmeros entre colchetes. As funes para mdia, mediana, varincia
e desvio padro so chamados de " dizer "," mdio "," variao "e" desvio padro ",
respectivamente. 1. A
mdia calcula a mdia de uma lista de nmeros - a lista deve ser entre colchetes:
>mdia ([3,6,4.2,7,7,2,3]);

Voc tambm pode nomear a lista antes do tempo (assim voc pode calcular mdia e varincia
sem digitar a lista duas vezes, por exemplo):
>Dados: = [3,6,4.2,7,7,2,3];

>mdia (dados);

2. A varincia funo tem a mesma sintaxe que a " significa a funo ", exceto que ele calcula a
varincia da lista:
>varincia ([3,6,4.2,7,7,2,3]);

>varincia (dados);

3. O desvio padro simplesmente a raiz quadrada da varincia, mas h tambm a funo de


bordo " desvio padro "para isso no" descrever subconjunto "do" estatsticas pacote ":
>desvio padro (dados);

Agora que voc ver o padro, voc pode descobrir como utilizar a funo de
bordo mediano para calcular a mediana de uma lista de dados.
Funes distribuio estatstica
H uma outra sub-pacote do estatsticas pacote que lida com distribuies de probabilidade que chamado statevalf , e ele deve ser carregado na memria do computador usando ambos os
comandos:
>(com estatsticas, statevalf);

>com (statevalf);

Os comandos dentro statevalf correspondem s operaes que se deseja executar em ambos


distribtions discretas de probabilidade (como a distribuio binomial) ou distribuies de
probabilidade contnuas (como a distribuio normal). As operaes so
1. Avaliar a funo densidade de probabilidade em um determinado valor para uma determinada
varivel aleatria.
2. Avaliar a funo de distribuio cumulativa em um determinado valor de uma varivel
aleatria (para determinar a probabilidade de que uma amostra aleatria ir produzir um valor
inferior ou igual ao valor dado). Esta operao responde a perguntas do formulrio "que a
probabilidade de que uma amostra a partir desta distribuio ser menor do que ou igual a x?".
3. Avaliar a "funo de distribuio cumulativa inversa" de uma varivel aleatria - isto como
procurar-se uma probabilidade no corpo do quadro de distribuio normal na parte de trs do
livro. Esta operao responde a perguntas da forma "Qual o valor de 95% da populao menor
que?".
1. Distribuies discretas:
variveis aleatrias discretas finitos assumir apenas um nmero finito de valores, como a soma
do que vem em dois dados, ou o nmero de moedas de um centavo que surgem cabeas quando
dez so viradas. De bordo compreende trs distribuies discretas que sero teis em
matemtica 151: "emprica", uniforme e binomial. A distribuio discreta uniforme denotado
"
discreteuniform [a, b] "em Maple. Neste distribuio, uma e b so nmeros inteiros, e a
distribuio determina probabilidades iguais aos nmeros inteiros de um a b (inclusive). Por
exemplo, a distribuio discreteuniform [1..6] designa a probabilidade de 1/6 para cada um dos
nmeros inteiros de 1 a 6 (isto a distribuio dos resultados de um rolamento de um par de
dados). Uma distribuio emprica um que est completamente especificado pela entrada do
utilizador. Por exemplo, a distribuio da soma das duas (justa) dice dada no texto Finitos
Math. Para comunicar esta distribuio de bordo, a notao correta :

emprica [op (evalF (0, 1/36, 2/36, 3/36, 4/36, 5/36, 6/36, 5/36, 4 / 36, 3/36, 2/36, 1/36))]
Isto indica que a probabilidade de x = 1 0, a probabilidade de x = 2 1/36, a probabilidade de
x = 3 e 2/36 assim por diante at que a probabilidade de x = 12, 1/36. Em outras palavras, os
doze nmeros na lista representam as probabilidades de um rolamento 1, 2, 3, ..., 12,
respectivamente. Por alguma razo, "emprica" s funciona quando voc usar nmeros de ponto
flutuante - que d mensagens de erro quando voc tenta colocar nas fraes reais. por isso que
h um " op (evalF (...)) "na demonstrao. Um no digite isso por si s como uma declarao de
bordo - ilustramos abaixo como us-lo. Finalmente, as distribuies binomial so indicados "
binomiald [n, p] "- esta notao tem o significado bvio. (Observe o "d" na grafia - deixando
isso ir resultar em uma mensagem de erro "distribuio solicitada no existe".) Agora
chegamos aos usos das
statevalf para cada uma dessas distribuies. Primeiro:
>pf [binomiald [5,0.3]] (2);

Isso indica que a probabilidade de obter 2 de 5 sucessos quando a probabilidade de sucesso em


cada tentativa de 0,3 0,30870. O " PF "na declarao indica que o que se deseja a
probabilidade de que a varivel aleatria exatamente igual ao nmero entre parnteses.
Como exemplo, considere o seguinte problema do livro Finitos Matemtica: "Em um
determinado distrito congressional, ele sabe-se que 40 por cento dos eleitores inscritos
classificam-se como conservadores. Se dez eleitores registrados so selecionados aleatoriamente
a partir deste distrito, qual a probabilidade de que quatro deles sero os conservadores?
" Desde dez eleitores so escolhidos, e que a probabilidade de escolher um conservador de 0,4,
a distribuio relevante a distribuio binomial com n = 10 e p = 0,4, em Maple este

binomiald [10,0.4] . Queremos que a probabilidade de que quatro das escolhas so


conservadores - para 4 vai nos parnteses. A resposta para o problema obtida atravs da
declarao de bordo:
>pf [binomiald [10,0.4]] (4);

A segunda maneira de utilizar statevalf com distribuies discretas para calcular a


distribuio cumulativa: esta a probabilidade de que uma varivel aleatria inferior ou igual
a um determinado valor. Para ilustrar, um outro problema a partir dos textos Finitos Matemtica
pergunta qual a probabilidade de que , no mximo, 8 de uma amostra aleatria de 20
fotoclulas esto com defeito, se sabido que 5% de todas as clulas produzidas so
defeituosas. A distribuio de probabilidade relevante a distribuio binomial com n = 20 e p
= 0,05, e queremos a probabilidade de que a varivel aleatria (nmero de defeituosos)
inferior ou igual a 8. A resposta obtido atravs do extracto de bordo:

>dcdf [binomiald [20,0.05]] (8);

Note-se que para obter " inferior ou igual a "usamos" dcdf "(que representa a funo de
distribuio cumulativa discreta). Para ilustrar a utilizao de uma distribuio emprica,
considerar a probabilidade de a enrolar um nmero inferior ou igual a 6, com um par de
dados. Ns definimos:
>dice: = emprica [op (evalF ([0,1 / 36,2 / 36,3 / 36,4 / 36,5 / 36,6 / 36,5 / 36, 4 / 36,3 / 36,2 /
36,1 / 36]))];

Em seguida, a probabilidade de obter 6 ou menos :


>dcdf [dados] (6);

2. distribuies contn

You might also like