Anonymous user
Verify distribution uniformity/Chi-squared test: Difference between revisions
Verify distribution uniformity/Chi-squared test (view source)
Revision as of 10:38, 13 May 2022
, 2 years ago→{{header|Fortran}}: Use gsl_cdf_chisq_Q, simplify code and enhance readability
m (→{{header|Phix}}: syntax coloured) |
(→{{header|Fortran}}: Use gsl_cdf_chisq_Q, simplify code and enhance readability) |
||
Line 410:
{{libheader|GNU Scientific Library}}
Instead of implementing the
<lang fortran>module
use iso_c_binding
implicit none
private
public :: p_value
interface
function gsl_cdf_chisq_q(x, nu) bind(c, name='gsl_cdf_chisq_Q')
import
real(c_double), value :: x
real(c_double), value :: nu
real(c_double) :: gsl_cdf_chisq_q
end function gsl_cdf_chisq_q
end interface
contains
!> Get p-value from chi-square distribution
real function p_value(x, df)
real, intent(in) :: x
integer, intent(in) :: df
p_value = real(gsl_cdf_chisq_q(real(x, c_double), real(df, c_double)))
end function p_value
end module gsl_mini_bind_m</lang>
Now we're ready to complete the task.
<lang fortran>program
use gsl_mini_bind_m, only: p_value
implicit none
real :: dset1(5) = [199809., 200665., 199607., 200270., 199649.]
real :: dset2(5) = [522573., 244456., 139979., 71531., 21461.]
real :: dist, prob
integer :: dof
write (*, '(A)', advance='no') "Dataset 1:"
write (*, '(5(F12.4,:,1x))') dset1
dist = chisq(dset1)
dof = size(dset1) - 1
write (*, '(A,I4,A,F12.4)') 'dof: ', dof, ' chisq: ', dist
prob = p_value(dist, dof)
write (*, '(A,F12.4)') 'probability: ', prob
write (*, '(A,L)') 'uniform? ', prob > 0.05
! Lazy copy/past :|
write (*, '(/A)', advance='no') "Dataset 2:"
write (*, '(5(F12.4,:,1x))') dset2
dist = chisq(dset2)
dof = size(dset2) - 1
write (*, '(A,I4,A,F12.4)') 'dof: ', dof, ' chisq: ', dist
prob = p_value(dist, dof)
write (*, '(A,F12.4)') 'probability: ', prob
write (*, '(A,L)') 'uniform? ', prob > 0.05
contains
!> Get chi-square value for a set of data `ds`
real
real, intent(in) :: ds(:)
real :: expected, summa
expected = sum(ds)/size(ds)
summa = sum((ds - expected)**2)
chisq = summa/expected
end function chisq
end program
=={{header|Go}}==
|