Statistics/Chi-squared distribution: Difference between revisions

→‎{{header|jq}}: use recursion formula for gamma
(→‎{{header|jq}}: simplify)
(→‎{{header|jq}}: use recursion formula for gamma)
Line 91:
{{works with|jq}}
'''Also works with gojq, the Go implementation of jq.'''
 
The implementation of Chi_cdf here uses the recusive relation for the
gamma function for efficiency and to simplify the avoidance of
numerical overflow issues.
 
'''Formatting'''
Line 120 ⟶ 124:
 
# $k is the degrees of freedom
# Use lgammarecursive torelation avoidfor $x^mgamma: G(forx+1) large= $x and* large mG(x) and
# to avoid calling gamma for large $k
def Chi2_cdf($x; $k):
if $x == 0 then 0
elif $x > (1e3 * $k) then 1
else 1e-15 as $tol # for example
| { s: 0, m: 0, term: (1 / ((($tolk/2)+1)|gamma)) }
| until (.term|length < $tol;
| .ms += 1).term
# .term = (pow($x/2; .m) / (($k/2 + .m + 1)|gamma))
| .m += 1
.term = (((.m * (($x/2)|log)) - (($k/2 + .m + 1)|lgamma)) | exp)
| .sterm +*= (($x/2) / (($k/2) + .termm )) )
| .terms =* (((.m * ((-$x/2)|log)) -+ (($k/2 + .m + 1)*(($x/2)|lgammalog)) | exp)
| .m += 1)
| .s * ( (-$x/2) + ($k/2)*(($x/2)|log)|exp)
end ;
 
</syntaxhighlight>
'''The Tasks'''
<syntaxhighlight lang=jq>
def tables:
def r: round(46) | lpad(10);
" Values of the χ2 probability distribution function",
" x/k 1 2 3 4 5",
Line 168 ⟶ 169:
 
tables,
airport(airport; expected)
</syntaxhighlight>
{{output}}
<pre>
Values of the χ2 probability distribution function
x/k 1 2 3 4 5
0 0 0 0 0 0
1 0.2420 241971 0.3033 303265 0.2420 241971 0.1516 151633 0.0807080657
2 0.1038 103777 0.1839 183940 0.2076 207554 0.1839 183940 0.1384138369
3 0.0514 051393 0.1116 111565 0.1542 154180 0.1673 167348 0.1542154180
4 0.0270 026995 0.0677 067668 0.1080 107982 0.1353 135335 0.1440143976
5 0.0146 014645 0.0410 041042 0.0732 073225 0.1026 102606 0.1220122042
6 0.0081 008109 0.0249 024894 0.0487 048652 0.0747 074681 0.0973097304
7 0.0046 004553 0.0151 015099 0.0319 031873 0.0528 052845 0.0744074371
8 0.0026 002583 0.0092 009158 0.0207 020667 0.0366 036631 0.0551055112
9 0.0015 001477 0.0056 005554 0.0133 013296 0.0250 024995 0.0399039887
10 0.0009 000850 0.0034 003369 0.0085 008500 0.0168 016845 0.0283028335
 
Values for χ2 with 3 degrees of freedom
χ2 cum pdf p-value
1 0.1987 198748 0.8013801252
2 0.4276 427593 0.5724572407
4 0.7385 738536 0.2615261464
8 0.9540 953988 0.0460046012
16 0.9989 998866 0.0011001134
32 0.999999 1.0000 0.00001e-06
 
For airport data table:
diff sum : 4.512820512820513
d.o.f. : 3
χ2 value : 0.08875392598443499088753925984435
p-value : 0.7889
</pre>
2,484

edits