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