using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Science.Statistics.BasicStatistics { public class ChiSquareTestForIndependence { private double[] of; private double[] ef; public ChiSquareTestForIndependence(double[,] table) { int cc = table.GetLength(0) * table.GetLength(1); df = (table.GetLength(0)-1) * (table.GetLength(1)-1); double[] rowsum = new double[table.GetLength(0)]; double[] columnsum = new double[table.GetLength(1)]; for (int i = 0; i < rowsum.Length; i++) { double sum = 0.0; for (int j = 0; j < columnsum.Length; j++) { sum += table[i, j]; } rowsum[i] = sum; } for (int j = 0; j < columnsum.Length; j++) { double sum = 0.0; for (int i = 0; i < rowsum.Length; i++) { sum += table[i, j]; } columnsum[j] = sum; } double total = 0.0; for (int i = 0; i < rowsum.Length; i++) { total += rowsum[i]; } FrequencyTable ft = new FrequencyTable(); for (int i = 0; i < rowsum.Length; i++) { for (int j = 0; j < columnsum.Length; j++) { ft.Add(table[i,j], rowsum[i]*columnsum[j]/total); } } OneSampleChiSquareTest test = new OneSampleChiSquareTest(ft, df); chsq = test.ChiSquare; pv = test.PValue; } private double chsq; public double ChiSquare { get { return chsq; } } private double pv; public double PValue { get { return pv; } } private int df; public int DegreesOfFreedom { get { return df; } } } }