CVD 0.8
cvd/random.h
00001 /*                       
00002     This file is part of the CVD Library.
00003 
00004     Copyright (C) 2005 The Authors
00005 
00006     This library is free software; you can redistribute it and/or
00007     modify it under the terms of the GNU Lesser General Public
00008     License as published by the Free Software Foundation; either
00009     version 2.1 of the License, or (at your option) any later version.
00010 
00011     This library is distributed in the hope that it will be useful,
00012     but WITHOUT ANY WARRANTY; without even the implied warranty of
00013     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
00014     Lesser General Public License for more details.
00015 
00016     You should have received a copy of the GNU Lesser General Public
00017     License along with this library; if not, write to the Free Software
00018     Foundation, Inc., 
00019     51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
00020 */
00021 #ifndef CVD_RANDOM_H
00022 #define CVD_RANDOM_H
00023 
00024 #include <cstdlib>
00025 #include <cmath>
00026 
00027 namespace CVD {
00032     inline double rand_u()
00033     {
00034         return ((double) std::rand()/ RAND_MAX);
00035     }
00036 
00041     inline double rand_g()
00042     {
00043         static bool use_old=false;
00044         static double y2;
00045         double r;
00046 
00047 
00048         if(!use_old)
00049         {
00050             double x1, x2, w, y1;
00051             do {
00052                 x1 = 2.0 * rand_u() - 1.0;
00053                 x2 = 2.0 * rand_u() - 1.0;
00054                 w = x1 * x1 + x2 * x2;
00055             } while ( w >= 1.0 );
00056 
00057             w = std::sqrt( (-2.0 * std::log( w ) ) / w );
00058             y1 = x1 * w;
00059             y2 = x2 * w;
00060 
00061             r = y1;
00062             use_old = true;
00063         }
00064         else
00065         {
00066             r = y2;
00067             use_old = false;
00068         }
00069 
00070 
00071         return r;
00072     }
00073 
00074 }
00075 
00076 #endif