Moe
Moe

Reputation: 4792

PHP Two Tailed Z-Score to P (Probability) Calculator

I've been searching all over and cannot find anything about this.

I'm looking for a function that will convert a Z-Score to a Probability using a two tailed table, preferably in PHP. (Like this one: http://www.sjsu.edu/faculty/gerstman/StatPrimer/z-two-tails.pdf)

My only other option is to make an array based on that table and comparing the Z-Score.. There must be a better way.

Edit:

Below is a slab of code found on the PHP.net statistics function page. These functions are really poorly documented. The functions below will accurately calculate a one-tailed z-score into a probability.

function erf($x)
{
    $pi = 3.1415927;
    $a = (8*($pi - 3))/(3*$pi*(4 - $pi));
    $x2 = $x * $x;

    $ax2 = $a * $x2;
    $num = (4/$pi) + $ax2;
    $denom = 1 + $ax2;

    $inner = (-$x2)*$num/$denom;
    $erf2 = 1 - exp($inner);

    return sqrt($erf2);
}

function cdf($n)
{
    if($n < 0)
    {
            return (1 - erf($n / sqrt(2)))/2;
    }
    else
    {
            return (1 + erf($n / sqrt(2)))/2;
    }
}

Upvotes: 2

Views: 780

Answers (1)

Moe
Moe

Reputation: 4792

Found a solution:

function erf($x)
{
    $pi = 3.1415927;
    $a = (8*($pi - 3))/(3*$pi*(4 - $pi));
    $x2 = $x * $x;

    $ax2 = $a * $x2;
    $num = (4/$pi) + $ax2;
    $denom = 1 + $ax2;

    $inner = (-$x2)*$num/$denom;
    $erf2 = 1 - exp($inner);

    return sqrt($erf2);
}

function cdf($n)
{
         return (1 - erf($n / sqrt(2)))/2;
         //I removed the $n < 0 test which inverses the +1/-1
}

function cdf_2tail($n)
{
        return 2*cdf($n);
            //After a little more digging around, the two tail test is simply 2 x the cdf.
}

I tested my results against: http://vassarstats.net/tabs.html#z and the z-score table.

It is correct to 0.1%

Upvotes: 4

Related Questions