# NMath Stats User's Guide

5.7 Pearson's Chi-Square Test (.NET, C#, CSharp, VB, Visual Basic, F#)

NMath Stats provides class for performing Pearson's chi-square test. Pearson's chi-square test is the most well-known of the chi-square tests, which are statistical procedures whose results are evaluated by reference to the chi-square distribution. It tests the null hypothesis that the frequency distribution of experimental outcomes are consistent with a particular theoretical distribution. The event outcomes considered must be mutually exclusive and have a total probability of 1.

Instances of PearsonsChiSquareTest are constructed either from raw data or tables of counts. For example, this code constructs a PearsonsChiSquareTest using outcomes from a series of experiment runs, along with the expected frequencies:

Code Example – C# chi-square test

```int[] outcomes = { 59, 20, 11, 10 };
DoubleVector probs =
new DoubleVector( 0.5625, 0.1875, 0.1875, 0.0625 );
PearsonsChiSquareTest test =
new PearsonsChiSquareTest( outcomes, probs );
```

This code uses a contingency table (or cross tabulation) to store the relation between two or more categorical variables:

Code Example – C# chi-square test

```var data = new int[2, 2];
data[0, 0] = 4298;
data[0, 1] = 767;
data[1, 0] = 7136;
data[1, 1] = 643;
bool yatesCorrect = true;
PearsonsChiSquareTest test =
new PearsonsChiSquareTest( data, yatesCorrect );
```

The Yates' correction for continuity may optionally be applied.

Once you've constructed and configured a PearsonsChiSquareTest object, you can access the various test results using the provided properties, as described in Section 5.1:

Code Example – C# chi-square test

```Console.WriteLine( "chi-square statistic = " +
test.ChiSquareStatistic );
Console.WriteLine( "numerator df = " + test.DegreesOfFreedom );
Console.WriteLine( "p-value = " + test.P );
Console.WriteLine( "reject the null hypothesis? " + test.Reject );
```

The output is:

```chi-square statistic = 147.761248704421
numerator df = 1
p-value = 0
reject the null hypothesis? True
```

Again, the ToString() method returns a formatted string representation of the complete test results:

```Pearson chi-square test
-----------------

Sample size = 12844
Yates corrected = True
Computed chi-square statistic: 147.761248704421, df = 1

P-value: 0
REJECT the null hypothesis for alpha = 0.01
```

Top

Top