contrib/mul/pdf1d/pdf1d_prob_chi2.cxx
Go to the documentation of this file.
00001 // This is mul/pdf1d/pdf1d_prob_chi2.cxx
00002 #include "pdf1d_prob_chi2.h"
00003 
00004 #include <vcl_iostream.h>
00005 #include <vcl_cstdlib.h> // for vcl_abort()
00006 #include <mbl/mbl_gamma.h>
00007 
00008 double pdf1d_chi2_for_cum_prob(double p, int n_dof, double tol)
00009 {
00010   if ((p<0) | (p>=1.0))
00011   {
00012     vcl_cerr<<"pdf1d_chi2_for_cum_prob : Illegal value for probability. (Outside range [0,1) )"<<vcl_endl;
00013     vcl_abort();
00014   }
00015 
00016   if (p==0) return 0;
00017 
00018   double d_step = n_dof; // prob = 50% ish
00019   double low_chi = 0;
00020   double high_chi = d_step;
00021 
00022   //double p_low = 0; // not used
00023   double p_high = pdf1d_cum_prob_chi2(n_dof,high_chi);
00024 
00025   // First step along till p_high >= p
00026   while (p_high<p)
00027   {
00028     low_chi = high_chi;
00029     // p_low = p_high; // not used
00030     high_chi += d_step;
00031     p_high = pdf1d_cum_prob_chi2(n_dof,high_chi);
00032   }
00033 
00034   // p_low and p_high now straddle answer
00035   double mid_chi = 0.5 * (low_chi+high_chi);
00036   double p_mid;
00037 
00038   while ((mid_chi-low_chi)>tol)
00039   {
00040     p_mid = pdf1d_cum_prob_chi2(n_dof,mid_chi);
00041     if (p_mid>p)
00042     {
00043       // Use low & mid as limits
00044       high_chi = mid_chi;
00045     }
00046     else
00047     {
00048       // Use mid and high as limits
00049       low_chi = mid_chi;
00050     }
00051 
00052     mid_chi = 0.5 * (low_chi+high_chi);
00053   }
00054 
00055   return mid_chi;
00056 }
00057 
00058 
00059 double pdf1d_cum_prob_chi2(int n_dof, double chi2)
00060 {
00061   return mbl_gamma_p((double) n_dof/2.0 , chi2/2.0 );
00062 }