Statistics/Chi-squared distribution: Difference between revisions

Created Nim solution.
m (→‎{{header|Wren}}: Wren-trait -> Wren-iterate)
(Created Nim solution.)
Line 305:
For the airport data, diff total is 4.512820512820512, χ2 is 0.08875392598443503, p value 0.7888504263193064
</pre>
 
=={{header|Nim}}==
{{libheader|gnuplotlib.nim}}
Adapted from Python solution.
<syntaxhighlight lang="Nim">import std/[math, strformat, sugar]
 
func χ²(x: float; k: int): float =
## χ² function, the probability distribution function (pdf) for χ².
if x > 0: x.pow(k / 2 - 1) * exp(-x/2) / (2.pow(k / 2) * gamma(k / 2)) else: 0
 
func gammaCdf(k, x: float): float =
## Lower incomplete gamma by series formula with gamma.
for m in 0..99:
result += x^m / gamma(k + m.toFloat + 1)
result *= pow(x, k) * exp(-x)
 
func cdfχ²(x: float; k: int): float =
## Cumulative probability function (cdf) for χ².
if x > 0 and k > 0: gammaCdf(k / 2, x / 2) else: 0
 
 
echo " Values of the χ2 probability distribution function"
echo " x/k 1 2 3 4 5"
for x in 0..10:
stdout.write &"{x:2} "
for k in 1..5:
stdout.write &"{χ²(x.toFloat, k):10.6f}"
echo()
 
echo()
echo " Values for χ2 with 3 degrees of freedom"
echo "χ² cum pdf p-value"
for x in [1, 2, 4, 8, 16, 32]:
let cdf = cdfχ²(x.toFloat, 3)
echo &"{x:2} {cdf:10.6f} {1 - cdf:10.6f}"
 
const
AirportData = [[float 77, 23], [float 88, 12], [float 79, 21], [float 81, 19]]
Expected = [[81.25, 18.75], [81.25, 18.75], [81.25, 18.75], [81.25, 18.75]]
 
var dtotal = 0.0
 
for pos in [0, 1]:
for i, d in AirportData:
dtotal += (d[pos] - Expected[i][pos])^2 / Expected[i][pos]
 
echo()
echo &"For the airport data, diff total is {dtotal:.6f}, " &
&"χ² is {χ²(dtotal, 3):.6f}, p value is {cdfχ²(dtotal, 3):.6f}."
 
 
### Stretch task ###
 
import gnuplot
let x = collect(for n in 0..9999: n / 1000)
withGnuplot:
cmd "set multiplot"
cmd "set yrange [-0.02:0.5]"
for k in 0..3:
let y = collect(for p in x: χ²(p, k))
plot(x, y, &"k = {k}", "with lines")
</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
χ² cum pdf 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 the airport data, diff total is 4.512821, χ² is 0.088754, p value is 0.788850.
</pre>
[[File:Chi-squared-nim.png]]
 
=={{header|Perl}}==
256

edits