# How can I compute the probability at a point given a normal distribution in Perl?

### Question

Is there a package in Perl that allows you to compute the height of probability distribution at each given point. For example this can be done in R this way:

``````> dnorm(0, mean=4,sd=10)
> 0.03682701
``````

Namely the probability of point x=0 falls into a normal distribution, with mean=4 and sd=10, is 0.0368. I looked at Statistics::Distribution but it doesn't give that very function to do it.

1
3
9/4/2009 4:54:58 PM

Why not something along these lines (I am writing in R, but it could be done in perl with Statistics::Distribution):

``````dn <- function(x=0 # value
,mean=0 # mean
,sd=1 # sd
,sc=10000 ## scale the precision
) {
res <- (pnorm(x+1/sc, mean=mean, sd=sd)-pnorm(x, mean=mean, sd=sd))*sc
res
}
> dn(0,4,10,10000)
0.03682709
> dn(2.02,2,.24)
1.656498
``````

[edit:1] I should mention that this approximation can get pretty horrible at the far tails. it might or might not matter depending on your application.

[edit:2] @foolishbrat Turned the code into a function. The result should always be positive. Perhaps you are forgetting that in the perl module you mention the function returns the upper probability 1-F, and R returns F?

[edit: 3] fixed a copy and paste error.

4
9/7/2009 3:31:18 AM

dnorm(0, mean=4, sd=10) does not give you thr probability of such a point occurring. To quote Wikipedia on probability density function

In probability theory, a probability density function (pdf)—often referred to as a probability distribution function1—or density, of a random variable is a function that describes the density of probability at each point in the sample space. The probability of a random variable falling within a given set is given by the integral of its density over the set.

and the probability you mention is

``````R> pnorm(0, 4, 10)
 0.3446
``````

or a 34.46% chance of getting a value equal to or smaller than 0 from a N(4, 10) distribution.

As for your Perl question: If you know how to do it in R, but need it from Perl, maybe you need to write a Perl extension based on R's libRmath (provided in Debian by the package r-mathlib) to get those functions to Perl? This does not require the R interpreter.

Otherwise, you could try the GNU GSL or the Cephes libraries for access to these special functions.