Jump to content

Statistics/Chi-squared distribution: Difference between revisions

Added Wren
(→‎{{header|Python}}: cleanup include)
(Added Wren)
Line 377:
 
For the airport data, diff total is 4.512820512820513, χ2 is 0.088753925984435, p value 0.7888504263193064
</pre>
 
=={{header|Wren}}==
{{libheader|Wren-math}}
{{libheader|Wren-fmt}}
<syntaxhighlight lang="ecmascript">import "./math" for Math
import "./fmt" for Fmt
 
class Chi2 {
static pdf(x, k) {
if (x <= 0) return 0
return (-x/2).exp * x.pow(k/2-1) / (2.pow(k/2) * Math.gamma(k/2))
}
 
static cpdf(x, k) {
var t = (-x/2).exp * (x/2).pow(k/2)
var s = 0
var m = 0
var tol = 1e-15 // say
while (true) {
var term = (x/2).pow(m) / Math.gamma(k/2 + m + 1)
s = s + term
if (term.abs < tol) break
m = m + 1
}
return t * s
}
}
 
System.print(" Values of the χ2 probability distribution function")
System.print(" x/k 1 2 3 4 5")
for (x in 0..10) {
Fmt.write("$2d ", x)
for (k in 1..5) {
Fmt.write("$f ", Chi2.pdf(x, k))
}
System.print()
}
 
System.print("\n Values for χ2 with 3 degrees of freedom")
System.print("χ2 cum cpdf p-value")
for (x in [1, 2, 4, 8, 16, 32]) {
var cpdf = Chi2.cpdf(x, 3)
Fmt.print("$2d $f $f", x, cpdf, 1-cpdf)
}
 
var airport = [[77, 23], [88, 12], [79, 21], [81, 19]]
var expected = [81.25, 18.75]
var dsum = 0
for (i in 0...airport.count) {
for (j in 0...airport[0].count) {
dsum = dsum + (airport[i][j] - expected[j]).pow(2) / expected[j]
}
}
var dof = (airport.count - 1) / (airport[0].count - 1)
System.print("\nFor airport data table: ")
Fmt.print(" diff sum : $f", dsum)
Fmt.print(" d.o.f. : $d", dof)
Fmt.print(" χ2 value : $f", Chi2.pdf(dsum, 3))
Fmt.print(" p-value : $f", Chi2.cpdf(dsum, 3))</syntaxhighlight>
 
{{out}}
<pre>
Values of the χ2 probability distribution function
x/k 1 2 3 4 5
0 0.000000 0.000000 0.000000 0.000000 0.000000
1 0.241971 0.303265 0.241971 0.151633 0.080657
2 0.103777 0.183940 0.207554 0.183940 0.138369
3 0.051393 0.111565 0.154180 0.167348 0.154180
4 0.026995 0.067668 0.107982 0.135335 0.143976
5 0.014645 0.041042 0.073225 0.102606 0.122042
6 0.008109 0.024894 0.048652 0.074681 0.097304
7 0.004553 0.015099 0.031873 0.052845 0.074371
8 0.002583 0.009158 0.020667 0.036631 0.055112
9 0.001477 0.005554 0.013296 0.024995 0.039887
10 0.000850 0.003369 0.008500 0.016845 0.028335
 
Values for χ2 with 3 degrees of freedom
χ2 cum cpdf p-value
1 0.198748 0.801252
2 0.427593 0.572407
4 0.738536 0.261464
8 0.953988 0.046012
16 0.998866 0.001134
32 0.999999 0.000001
 
For airport data table:
diff sum : 4.512821
d.o.f. : 3
χ2 value : 0.088754
p-value : 0.788850
</pre>
9,490

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.