Some questions on pow and random

Mark Dickinson dickinsm at gmail.com
Sun Mar 27 07:31:33 EDT 2011


On Mar 27, 11:07 am, joy99 <subhakolkata1... at gmail.com> wrote:
> (i) By standard definition of Likelihood Estimation, we get if x EURO X,
> where X is a countable set of types, p is probability and f is
> frequency.
> L(f;p)=Ðp(x)f(x)
>
> My question is python provides two functions,
> (a)     pow for power.
> (b)     reduce(mul, list)
>
> Now, how to combine them? If any one can suggest any help?

If I'm understanding your question correctly, it sounds as though
you've got a vector p = (p_1, p_2, ..., p_n) of probabilities and a
corresponding vector f = (f_1, f_2, ..., f_n) of integer frequencies,
and you want to compute the product of the quantities p_i ** f_i.  Is
that right?

Assuming that p and f are represented by Python lists, you might do
something like this:

>>> p = [0.1, 0.5, 0.4]
>>> f = [3, 24, 18]
>>> product = 1.0
>>> for pi, fi in zip(p, f):
...     product *= pi**fi
...
>>> product
4.096000000000005e-18

I wouldn't particularly recommend using 'reduce' for this, since it
doesn't lead to readable code, but if you must you can do:

>>> import operator
>>> reduce(operator.mul, map(pow, p, f), 1)
4.096000000000005e-18

or:

>>> reduce(operator.mul, [pi**fi for pi, fi in zip(p, f)], 1)
4.096000000000005e-18

> As p(x)f(x), would be huge would pow support it?

You'll run into problems with underflow to zero fairly quickly.  The
usual solution is to work with log likelihood instead of likelihood
itself, in which case you'd want a sum instead:

>>> sum(fi*log(pi) for pi, fi in zip(p, f))
-40.03652078615561

If you really need the likelihood itself, you might try using the
Decimal module, which allows a much wider exponent range than Python's
builtin float.

--
Mark



More information about the Python-list mailing list