//---------------------------------------------------------------------------- int f_root4p(REAL p1,REAL p2,REAL p3,REAL a,REAL b,REAL (*fp)(REAL, void*), REAL * result){ struct f_params_3 alpha = {p1,p2,p3}; int status; int iter = 0, max_iter = 1000; REAL r = 0.0; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; gsl_function F; F.function = fp; F.params = α T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s,&F,a,b); do{ iter++; status = gsl_root_fsolver_iterate(s); r = gsl_root_fsolver_root(s); a = gsl_root_fsolver_x_lower(s); b = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(a,b,0,0.001); }while (status == GSL_CONTINUE && iter < max_iter); *result=r; gsl_root_fsolver_free (s); return 0; }
double fzero( function<double(double)> fun, double x_lo, double x_hi, int max_iter, double epsabs, double epsrel ) { // Allocate gsl_function F = { gsl::sfunction_proxy, &fun }; const gsl_root_fsolver_type *T = gsl_root_fsolver_brent; gsl_root_fsolver *s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set( s, &F, x_lo, x_hi ); // Main loop int status; double rv; int iter = 0; do { iter++; status = gsl_root_fsolver_iterate(s); rv = gsl_root_fsolver_root(s); x_lo = gsl_root_fsolver_x_lower(s); x_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval( x_lo, x_hi, epsabs, epsrel ); } while (status == GSL_CONTINUE && iter < max_iter); if( iter == max_iter ) warning("bealab::fzero - maximum number of iterations reached"); // Free gsl_root_fsolver_free (s); return rv; }
double root_finder( double (*f)(double), double a, double b, double epsrel, double epsabs ) { int status,i; double root; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; gsl_function F; F.function = gsl_function_wrapper; F.params = (void *)f; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, a, b); for ( i = 0; i < MAX_ITER; i++ ) { status = gsl_root_fsolver_iterate (s); status = gsl_root_test_interval (gsl_root_fsolver_x_lower(s), gsl_root_fsolver_x_upper(s), epsrel, epsabs); if (status == GSL_SUCCESS) { root = gsl_root_fsolver_root(s); gsl_root_fsolver_free(s); return root; } } cart_error("Did not reach root after %u iterations!", MAX_ITER); return 0.0; }
//_______________________________________________________________________________________________________________________ /// /// \brief Calculate chemical potential 'mu' such that FermiDirac distribution gives exactly 'nelec' electrons /// static double CalculateChemicalPotential(const en_levels_t *levels, const int nelec, const bool spinpol, const double kBT) { int m, n, i; const int maxiter = 128; gsl_FD_params_t params; params.nelec = nelec; params.nlevels = (levels->m_max+1)*levels->num; params.en = malloc(params.nlevels * sizeof(double)); params.occ = malloc(params.nlevels * sizeof(int)); params.kBT = kBT; // fill energy levels and occupancies for (m = 0; m <= levels->m_max; m++) { for (n = 0; n < levels->num; n++) { params.en [n + m*levels->num] = levels->en[n + m*levels->num]; params.occ[n + m*levels->num] = GetMaxOccupancy(m, spinpol); } } // first interval used in interval bisection method double mu_lo = 0.0; double mu_hi = levels->en[(levels->m_max+1)*levels->num-1]; // use "last" energy level as upper bound gsl_function F; F.function = &NumParticleDifference; F.params = ¶ms; const gsl_root_fsolver_type *T = gsl_root_fsolver_brent; gsl_root_fsolver *s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s, &F, mu_lo, mu_hi); double mu = 0; int status = GSL_CONTINUE; for (i = 0; i < maxiter && status == GSL_CONTINUE; i++) { status = gsl_root_fsolver_iterate(s); if (status != GSL_SUCCESS) { fprintf(stderr, "CalculateOccupancy() warning: gsl_root_fsolver_iterate() returned with status code %i\n", status); } mu = gsl_root_fsolver_root(s); mu_lo = gsl_root_fsolver_x_lower(s); mu_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(mu_lo, mu_hi, 0, 1e-8); } if (status != GSL_SUCCESS) { fprintf(stderr, "CalculateOccupancy() warning: not converged after %i iterations, status: %i\n", maxiter, status); } // clean up free(params.occ); free(params.en); gsl_root_fsolver_free(s); return mu; }
/* this function returns the solution to f (x) = 0 */ int f_root (double x_min, double x_max, double *root, struct f_root_params *par) { size_t iter; int status; double x_lo, x_hi; gsl_root_fsolver *s; /* defines the function to pass to the solver */ gsl_function func; func.function = par->f; func.params = par->p; /* allocates and initializes the minimizer */ s = gsl_root_fsolver_alloc (par->type); gsl_root_fsolver_set (s, &func, x_min, x_max); /* start the iteration to find the root */ iter = 0; do { iter++; status = gsl_root_fsolver_iterate (s); *root = gsl_root_fsolver_root (s); x_lo = gsl_root_fsolver_x_lower (s); x_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x_lo, x_hi, par->eps_abs, par->eps_rel); if (par->verbose) fprintf (stderr, "%lu: x = %f\n", iter, *root); } while (status==GSL_CONTINUE && iter<par->max_iter); /* free the memory and return the found root */ gsl_root_fsolver_free (s); return status; }
double root(double begin) { int status; int iter = 0, max_iter = 100000; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double x_lo = begin / 2, x_hi = begin - e, r; gsl_function F; F.function = &f; F.params = &begin; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, x_lo, x_hi); do { iter++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); x_lo = gsl_root_fsolver_x_lower (s); x_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x_lo, x_hi, 0, e); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return r; }
const Real GreensFunction2DAbs::drawTime(const Real rnd) const { THROW_UNLESS(std::invalid_argument, 0.0<=rnd && rnd <= 1.0); if(D == 0e0 || a == std::numeric_limits<Real>::infinity() || rnd == 1e0) return std::numeric_limits<Real>::infinity(); if(a == r0 || rnd == 0e0) return 0e0; p_survival_params params = {this, rnd}; gsl_function F = { reinterpret_cast<double (*)(double, void*)>(&p_survival_F), ¶ms }; // this is not so accurate because // initial position is not the center of this system. const Real t_guess(a * a * 0.25 / D); Real value(GSL_FN_EVAL(&F, t_guess)); Real low(t_guess); Real high(t_guess); // to determine high and low border if(value < 0.0) { do { high *= 1e1; value = GSL_FN_EVAL(&F, high); if(fabs(high) > t_guess * 1e6) throw std::invalid_argument("could not adjust higher border"); } while(value <= 0e0); } else { Real value_prev = value; do { low *= 1e-1; value = GSL_FN_EVAL(&F, low); if(fabs(low) <= t_guess * 1e-6 || fabs(value - value_prev) < CUTOFF) throw std::invalid_argument("could not adjust lower border"); value_prev = value; } while(value >= 0e0); } //find the root const gsl_root_fsolver_type* solverType(gsl_root_fsolver_brent); gsl_root_fsolver* solver(gsl_root_fsolver_alloc(solverType)); const Real t(findRoot(F, solver, low, high, 1e-18, 1e-12, "GreensFunction2DAbs::drawTime")); gsl_root_fsolver_free(solver); return t; }
const Real GreensFunction2DAbs::drawTheta(const Real rnd, const Real r, const Real t) const { THROW_UNLESS(std::invalid_argument, 0.0<=rnd && rnd <= 1.0); if(rnd == 1e0) return 2e0 * M_PI; if(fabs(r) < CUTOFF)// r == 0e0 ? { throw std::invalid_argument( (boost::format("2DAbs::drawTheta r is too small: r=%f10") % r).str()); } if(fabs(r-a) < CUTOFF)// r == a ? { //when R equal a, p_int_theta is zero at any theta throw std::invalid_argument( (boost::format("2DAbs::drawTheta r is nealy a: r=%f10, a=%f10") % r % a).str()); } if(t == 0e0 || D == 0e0) return 0e0; Real int_2pi = p_int_2pi(r, t); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * When t is too large, int_2pi become zero and drawR returns 2pi * * at any value of rnd. To avoid this, return rnd * theta / 2pi * * because when t -> \infty the probability density function of theta* * become uniform distribution * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ if(int_2pi == 0e0) { std::cout << dump(); std::cout << "Warning: t is too large. t = " << t << std::endl; } p_theta_params params = {this, t, r, rnd * int_2pi}; gsl_function F = { reinterpret_cast<double (*)(double, void*)>(&p_theta_F), ¶ms }; const Real low(0e0); const Real high(2e0 * M_PI); const gsl_root_fsolver_type* solverType(gsl_root_fsolver_brent); gsl_root_fsolver* solver(gsl_root_fsolver_alloc(solverType)); const Real theta(findRoot(F, solver, low, high, 1e-18, 1e-12, "GreensFunction2DAbsSym::drawTheta")); gsl_root_fsolver_free(solver); return theta; }
CAMLprim value ml_gsl_root_fsolver_free(value s) { struct callback_params *p=Fparams_val(s); remove_global_root(&(p->closure)); stat_free(p); gsl_root_fsolver_free(Fsolver_val(s)); return Val_unit; }
void test_f (const gsl_root_fsolver_type * T, const char * description, gsl_function *f, double lower_bound, double upper_bound, double correct_root) { int status; size_t iterations = 0; double r, a, b; double x_lower, x_upper; gsl_root_fsolver * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s, f, x_lower, x_upper) ; do { iterations++ ; gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root(s); a = gsl_root_fsolver_x_lower(s); b = gsl_root_fsolver_x_upper(s); if (a > b) gsl_test (GSL_FAILURE, "interval is invalid (%g,%g)", a, b); if (r < a || r > b) gsl_test (GSL_FAILURE, "r lies outside interval %g (%g,%g)", r, a, b); status = gsl_root_test_interval (a,b, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (status, "%s, %s (%g obs vs %g expected) ", gsl_root_fsolver_name(s), description, gsl_root_fsolver_root(s), correct_root); if (iterations == MAX_ITERATIONS) { gsl_test (GSL_FAILURE, "exceeded maximum number of iterations"); } /* check the validity of the returned result */ if (!WITHIN_TOL (r, correct_root, EPSREL, EPSABS)) { gsl_test (GSL_FAILURE, "incorrect precision (%g obs vs %g expected)", r, correct_root); } gsl_root_fsolver_free(s); }
void Spectrometer::calibrate(){ if(calibration.size()!=2) return; double a=1e3; // grating step in nm double l1 = calibration[0].wavelength; double x1 = calibration[0].pixelNum-imageWidth/2.; double l2 = calibration[1].wavelength; double x2 = calibration[1].pixelNum-imageWidth/2.; struct calcFParams params = {l1,l2,x1,x2,a}; double f_lo= 200; double f_hi= 3000; gsl_function F; F.function = &Spectrometer::calcFFunc; F.params = ¶ms; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; //T = gsl_root_fsolver_brent; T = gsl_root_fsolver_bisection; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set (s, &F, f_lo, f_hi); //f in pixels guessed to be between 300 and 5000 double r=500; int iter=0; int max_iter=100; int status; do{ iter++; status = gsl_root_fsolver_iterate(s); r = gsl_root_fsolver_root(s); f_lo = gsl_root_fsolver_x_lower(s); f_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval (f_lo, f_hi, 0, 0.001); } while (status == GSL_CONTINUE && iter < max_iter); if(status==GSL_SUCCESS) { focal = r; pas = a; sin_angle_i = l1/pas + x1/sqrt(r*r+x1*x1); isXCalibrated = true; qDebug()<<"Calibration finished !"; qDebug()<<"focal : "<< focal; qDebug()<<"angle i : "<< 180/3.1415*asin(sin_angle_i); qDebug()<<"angle i2 : "<< 180/3.1415*asin( l2/pas + x2/sqrt(r*r+x2*x2)); } gsl_root_fsolver_free (s); }
void test_f_e (const gsl_root_fsolver_type * T, const char * description, gsl_function *f, double lower_bound, double upper_bound, double correct_root) { int status; size_t iterations = 0; double x_lower, x_upper; gsl_root_fsolver * s; x_lower = lower_bound; x_upper = upper_bound; s = gsl_root_fsolver_alloc(T); status = gsl_root_fsolver_set(s, f, x_lower, x_upper) ; gsl_test (status != GSL_EINVAL, "%s (set), %s", T->name, description); if (status == GSL_EINVAL) { gsl_root_fsolver_free(s); return ; } do { iterations++ ; gsl_root_fsolver_iterate (s); x_lower = gsl_root_fsolver_x_lower(s); x_upper = gsl_root_fsolver_x_lower(s); status = gsl_root_test_interval (x_lower, x_upper, EPSABS, EPSREL); } while (status == GSL_CONTINUE && iterations < MAX_ITERATIONS); gsl_test (!status, "%s, %s", gsl_root_fsolver_name(s), description, gsl_root_fsolver_root(s) - correct_root); gsl_root_fsolver_free(s); }
/// Get the cDel for a given cvir double cosmology::getcDel(double cvir, double z, double Delta) { int status; int iter = 0, max_iter = 100; double res; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double c_lo = 0.01*cvir, c_hi = 10.0*cvir; gsl_function F; cDel_params p; p.cptr = this; p.cvir = &cvir; double omz=Omega(z); double dcz=Delta_crit(z); p.omegaz=&omz; p.dcz=&dcz; p.Delta=Δ F.function = &findcDel; F.params = &p; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, c_lo, c_hi); do { iter++; status = gsl_root_fsolver_iterate (s); res = gsl_root_fsolver_root (s); c_lo = gsl_root_fsolver_x_lower (s); c_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (c_lo, c_hi,0, 1e-6); if (status == GSL_SUCCESS) { //std::cout<<"# "<<"zcollapse:Brent converged after "<< iter<<" iterations"<<std::endl; } }while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return res; }
int main (void) { int status; int iter = 0, max_iter = 100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double r = 0, r_expected = sqrt (5.0); double x_lo = 0.0, x_hi = 5.0; gsl_function F; struct quadratic_params params = {1.0, 0.0, -5.0}; F.function = &quadratic; F.params = ¶ms; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, x_lo, x_hi); printf ("using %s method\n", gsl_root_fsolver_name (s)); printf ("%5s [%9s, %9s] %9s %10s %9s\n", "iter", "lower", "upper", "root", "err", "err(est)"); do { iter++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); x_lo = gsl_root_fsolver_x_lower (s); x_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x_lo, x_hi, 0, 0.001); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5d [%.7f, %.7f] %.7f %+.7f %.7f\n", iter, x_lo, x_hi, r, r - r_expected, x_hi - x_lo); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return status; }
const Real findRoot( gsl_function& F, gsl_root_fsolver* solver, const Real low, const Real high, const Real tol_abs, const Real tol_rel, std::string funcName ) { Real l( low ); Real h( high ); gsl_root_fsolver_set( solver, &F, l, h ); const unsigned int maxIter( 100 ); unsigned int i( 0 ); while( true ) { gsl_root_fsolver_iterate( solver ); l = gsl_root_fsolver_x_lower( solver ); h = gsl_root_fsolver_x_upper( solver ); const int status( gsl_root_test_interval( l, h, tol_abs, tol_rel ) ); if( status == GSL_CONTINUE ) { if( i >= maxIter ) { gsl_root_fsolver_free( solver ); std::cerr << funcName << ": failed to converge." << std::endl; throw std::exception(); } } else { break; } ++i; } const Real root( gsl_root_fsolver_root( solver ) ); return root; }
/* compute the first N roots alpha_k of the equation ((A-1)/(A+1)) cos((H - Z B) alpha) = cos((H + Z B) alpha) where H and B are heights and A, Z are defined in terms of material constants */ int print_alpha_k(const int N) { int status, iter, k, max_iter = 200; double Z, A; double alpha, alpha_lo, alpha_hi, temp_lo; const gsl_root_fsolver_type *solvT; gsl_root_fsolver *solv; gsl_function F; struct coscross_params params; Z = sqrt((rho_BR * c_p_BR * k_ICE) / (rho_ICE * c_p_ICE * k_BR)); A = (k_BR / k_ICE) * Z; params.Afrac = (A - 1.0) / (A + 1.0); params.HZBsum = H0 + Z * B0; params.HZBdiff = H0 - Z * B0; F.function = &coscross; F.params = ¶ms; solvT = gsl_root_fsolver_brent; /* faster than bisection but still bracketing */ solv = gsl_root_fsolver_alloc(solvT); for (k = 0; k < N; k++) { /* these numbers bracket exactly one solution */ alpha_lo = (double(k) * pi) / params.HZBsum; alpha_hi = (double(k + 1) * pi) / params.HZBsum; gsl_root_fsolver_set(solv, &F, alpha_lo, alpha_hi); iter = 0; do { iter++; status = gsl_root_fsolver_iterate(solv); alpha = gsl_root_fsolver_root(solv); alpha_lo = gsl_root_fsolver_x_lower(solv); alpha_hi = gsl_root_fsolver_x_upper(solv); temp_lo = (alpha_lo > 0) ? alpha_lo : (alpha_hi/2.0); status = gsl_root_test_interval(temp_lo, alpha_hi, 0, ALPHA_RELTOL); } while ((status == GSL_CONTINUE) && (iter < max_iter)); if (iter >= max_iter) { printf("!!!ERROR: root finding iteration reached maximum iterations; QUITING!\n"); return ITER_MAXED_OUT; } printf("%19.15e,\n",alpha); /* DEBUG: printf("%19.15e (in orig bracket [%19.15e,%19.15e])\n",alpha, (double(k) * pi) / params.HZBsum, (double(k+1) * pi) / params.HZBsum); */ } gsl_root_fsolver_free(solv); return status; }
// Iterates the solver until desired precision has been reached or a maximum // number of iterations have been performed. Real findRoot(gsl_function const& F, gsl_root_fsolver* solver, Real low, Real high, Real tol_abs, Real tol_rel, char const* funcName) { // low and high should constitute an interval that straddles a root. Real l(low); Real h(high); gsl_root_fsolver_set(solver, const_cast<gsl_function*>(&F), l, h); const unsigned int maxIter(100); unsigned int i(0); for (;;) { // iterate gsl_root_fsolver_iterate(solver); // get found bracketing interval l = gsl_root_fsolver_x_lower(solver); h = gsl_root_fsolver_x_upper(solver); // see if this is acceptable const int status(gsl_root_test_interval(l, h, tol_abs, tol_rel)); // stop finder if convergence or too much iterations if (status == GSL_CONTINUE) { if (i >= maxIter) { gsl_root_fsolver_free(solver); throw std::runtime_error(std::string(funcName) + ": failed to converge"); } } else { break; } ++i; } const Real root(gsl_root_fsolver_root(solver)); return root; }
static VALUE rb_gsl_function_rootfinder(int argc, VALUE *argv, VALUE obj) { int status, iter = 0, max_iter = 1000; const gsl_root_fsolver_type *T; gsl_root_fsolver *s = NULL; gsl_function *F = NULL; double r, a, b, epsabs = 0.0, epsrel = 1e-6; Data_Get_Struct(obj, gsl_function, F); switch (argc) { case 2: a = NUM2DBL(argv[0]); b = NUM2DBL(argv[1]); break; case 1: switch (TYPE(argv[0])) { case T_ARRAY: a = NUM2DBL(rb_ary_entry(argv[0], 0)); b = NUM2DBL(rb_ary_entry(argv[0], 1)); break; default: rb_raise(rb_eTypeError, "interval must be given by an array [a, b]"); } break; default: rb_raise(rb_eArgError, "interval must be given"); break; } T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, F, a, b); do { iter++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); a = gsl_root_fsolver_x_lower (s); b = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (a, b, epsabs, epsrel); if (status == GSL_SUCCESS) break; } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free(s); if (status == GSL_SUCCESS) { return rb_ary_new3(3, rb_float_new(r), INT2FIX(iter), INT2FIX(status)); } else { printf("not converged\n"); return Qfalse; } }
/// Get the Mvir for a given MDel double cosmology::getMvir(double M, double z,double Delta) { int status; int iter = 0, max_iter = 100; double res; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double m_lo = 0.1*M, m_hi = 5.0*M; gsl_function F; mvir_params p; p.cptr = this; p.mDel = &M; p.z=&z; p.Delta=Δ F.function = &findmvir; F.params = &p; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, m_lo, m_hi); do { iter++; status = gsl_root_fsolver_iterate (s); res = gsl_root_fsolver_root (s); m_lo = gsl_root_fsolver_x_lower (s); m_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (m_lo, m_hi,0, 1.e-6); if (status == GSL_SUCCESS) { //std::cout<<"# "<<"zcollapse:Brent converged after "<< iter<<" iterations"<<std::endl; } }while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return res; }
/// Get the c200 for a given cvir double cosmology::getcDeltap_from_cDelta(double cDelta, double Delta, double Deltap) { int status; int iter = 0, max_iter = 100; double res; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double c_lo = 0.01*cDelta, c_hi = 10.0*cDelta; gsl_function F; cDelta_params p; double frac=Delta/Deltap; p.cDelta = &cDelta; p.frac = &frac; F.function = &findcDelp; F.params = &p; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, c_lo, c_hi); do { iter++; status = gsl_root_fsolver_iterate (s); res = gsl_root_fsolver_root (s); c_lo = gsl_root_fsolver_x_lower (s); c_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (c_lo, c_hi,0, 1e-6); if (status == GSL_SUCCESS) { //std::cout<<"# "<<"zcollapse:Brent converged after "<< iter<<" iterations"<<std::endl; } }while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return res; }
/// Get the M which has N_{+} number of haloes above mass M. double cosmology::getM(double Np,double z) { int status; int iter = 0, max_iter = 100; double res; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; // m is in log_{10}(m) double xm_lo = 9.0, xm_hi = 15.5; gsl_function F; np_params p; p.cptr = this; p.z = &z; p.Np = &Np; F.function = &findM; F.params = &p; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, xm_lo, xm_hi); do { iter++; status = gsl_root_fsolver_iterate (s); res = gsl_root_fsolver_root (s); xm_lo = gsl_root_fsolver_x_lower (s); xm_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (xm_lo, xm_hi,0, 1e-6); if (status == GSL_SUCCESS) { std::cout<<"# "<<"getM:Brent converged after "<< iter<<" iterations"<<std::endl; } }while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return pow(10.,res); }
/// Get the collapse redshift for a given variance double cosmology::getzcoll(double sigma) { int status; int iter = 0, max_iter = 100; double res; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double z_lo = 0.0, z_hi = 10.0; gsl_function F; coll_params p; p.cptr = this; p.sig = σ F.function = &findzcoll; F.params = &p; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set (s, &F, z_lo, z_hi); do { iter++; status = gsl_root_fsolver_iterate (s); res = gsl_root_fsolver_root (s); z_lo = gsl_root_fsolver_x_lower (s); z_hi = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (z_lo, z_hi,0, 1e-6); if (status == GSL_SUCCESS) { //std::cout<<"# "<<"zcollapse:Brent converged after "<< iter<<" iterations"<<std::endl; } }while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return res; }
// Calculates the roots of tan(x*a)=-x/h Real GreensFunction1DRadAbs::root_n(int n) const { const Real L( this->geta()-this->getsigma() ); const Real h( (this->getk()+this->getv()/2.0) / this->getD() ); // the drift v also comes into this constant, h=(k+v/2)/D Real upper, lower; if ( h*L < 1 ) { // 1E-10 to make sure that he doesn't include the transition lower = (n-1)*M_PI + 1E-10; // (asymptotic) from infinity to -infinity upper = n *M_PI - 1E-10; } else { lower = (n-1)*M_PI + M_PI_2 + 1E-10; upper = n *M_PI + M_PI_2 - 1E-10; } gsl_function F; struct tan_f_params params = { L, h }; F.function = &GreensFunction1DRadAbs::tan_f; F.params = ¶ms; // define a new solver type brent const gsl_root_fsolver_type* solverType( gsl_root_fsolver_brent ); // make a new solver instance // TODO: incl typecast? gsl_root_fsolver* solver( gsl_root_fsolver_alloc( solverType ) ); // get the root = run the rootsolver const Real root( findRoot( F, solver, lower, upper, 1.0*EPSILON, EPSILON, "GreensFunction1DRadAbs::root_tan" ) ); gsl_root_fsolver_free( solver ); return root/L; // This rescaling is important, because the function tan_f is used to solve for // tan(x)+x/h/L=0, whereas we actually need tan(x*L)+x/h=0, So if x solves the // subsidiary equation, x/L solves the original one. }
double raytrace_free_distance(scope_ray ray, raytrace_geom geom, int surf){ /* Variable declarations */ /* Variables needed for GSL's root-finder algorithms */ int status; int iter = 0, max_iter = 100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; double r = 0; double x_lo = 0.0, x_hi = 5.0; gsl_function F; scope_root_params params = {ray, geom, surf}; /* If w/in Rowland Circle, reduce x_hi to 2.1 */ if(surf == OPTIC_SF) x_hi = 2.1; F.function = &raytrace_distroot; F.params = ¶ms; /* Solve using GSL's Brent's Method Solver */ // T = gsl_root_fsolver_brent; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc(T); gsl_root_fsolver_set(s, &F, x_lo, x_hi); do{ iter++; status = gsl_root_fsolver_iterate(s); r = gsl_root_fsolver_root(s); x_lo = gsl_root_fsolver_x_lower(s); x_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(x_lo, x_hi, 0, 1.e-14); } while (status == GSL_CONTINUE && iter < max_iter); gsl_root_fsolver_free (s); return r; }
// Calculates the roots of tan(aL)=-ak/h const Real FirstPassageGreensFunction1DRad::a_n(const int n) const { // L=length of domain=2*a const Real L(this->getL()); // h=k/D const Real h(this->getk()/this->getD()); Real upper, lower; if ( h*L < 1 ) { // 1E-10 to make sure that he doesn't include the transition lower = (n-1)*M_PI + 1E-10; // (asymptotic) from infinity to -infinity upper = n *M_PI - 1E-10; } else { lower = (n-1)*M_PI + M_PI_2 + 1E-10; upper = n *M_PI + M_PI_2 - 1E-10; } gsl_function F; struct tan_f_params params = { L, h}; F.function = &FirstPassageGreensFunction1DRad::tan_f; F.params = ¶ms; // define a new solver type brent const gsl_root_fsolver_type* solverType( gsl_root_fsolver_brent ); // make a new solver instance // incl typecast? gsl_root_fsolver* solver( gsl_root_fsolver_alloc( solverType ) ); const Real a( findRoot( F, solver, lower, upper, 1.0*EPSILON, EPSILON, "FirstPassageGreensFunction1DRad::root_tan" ) ); gsl_root_fsolver_free( solver ); return a; }
/** * GSL's the Brent-Dekker method (referred to here as Brent's method) combines an * interpolation strategy with the bisection algorithm. This produces a fast algorithm * which is still robust.On each iteration Brent's method approximates the function * using an interpolating curve. On the first iteration this is a linear interpolation * of the two endpoints. For subsequent iterations the algorithm uses an inverse quadratic * fit to the last three points, for higher accuracy. The intercept of the interpolating * curve with the x-axis is taken as a guess for the root. If it lies within the bounds * of the current interval then the interpolating point is accepted, and used to generate * a smaller interval. If the interpolating point is not accepted then the algorithm falls * back to an ordinary bisection step. * * The best estimate of the root is taken from the most recent interpolation or bisection. * * @author Sharmila Prasad (9/15/2011) * * @param x_lo - Initial lower search interval * @param x_hi - Initial higher search interval * @param Func - Continuous function of one variable for the root finders to operate on * @param tolerance - Root Error Tolerance * @param root - Output calculated root * * @return int - Algorithm status */ int Photometry::brentsolver(double x_lo, double x_hi, gsl_function *Func, double tolerance, double &root){ int status; int iter=0, max_iter=100; const gsl_root_fsolver_type *T; gsl_root_fsolver *s; T = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (T); gsl_root_fsolver_set(s, Func, x_lo, x_hi); do { iter++; status = gsl_root_fsolver_iterate(s); root = gsl_root_fsolver_x_lower(s); x_lo = gsl_root_fsolver_x_lower(s); x_hi = gsl_root_fsolver_x_upper(s); status = gsl_root_test_interval(x_lo, x_hi, 0, tolerance); } while (status != GSL_SUCCESS && iter < max_iter); gsl_root_fsolver_free(s); return status; }
void conf(Args *args, Result *result){ const gsl_root_fsolver_type *solverType; gsl_root_fsolver *s; gsl_function fun; double xLo, xHi; int status; /* preliminaries */ gsl_set_error_handler_off(); fun.function = &confFun; fun.params = result; solverType = gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc(solverType); /* search for lower bound of delta */ result->type = 2; if(result->de < 0) xLo = -1; else xLo = 0; xHi = result->de; status = gsl_root_fsolver_set(s,&fun,xLo,xHi); if(status){ printf("WARNING: Lower confidence limit of \\Delta cannot be estimated; setting it to -1.\n"); result->dLo = -1.0; }else result->dLo = iterate(args, s, xLo, xHi); /* search for upper bound of delta */ xLo = result->de; xHi = 1.0; status = gsl_root_fsolver_set(s,&fun,xLo,xHi); if(status){ printf("WARNING: Upper confidence limit of \\Delta cannot be estimated; setting it to 1.\n"); result->dUp = 1; }else result->dUp = iterate(args, s, xLo, xHi); gsl_root_fsolver_free(s); }
const Real GreensFunction2DAbs::drawR(const Real rnd, const Real t) const { THROW_UNLESS(std::invalid_argument, 0.0<=rnd && rnd <= 1.0); if(a == r0) throw std::invalid_argument("a equal r0"); if(t == 0e0 || D == 0e0) return r0; if(rnd == 1e0) return a;//!? Real p_surv(p_survival(t)); assert(p_surv > 0e0); p_r_params params = {this, t, rnd * p_surv}; gsl_function F = { reinterpret_cast<double (*)(double, void*)>(&p_r_F), ¶ms }; const Real low(0e0); const Real high(a); const gsl_root_fsolver_type* solverType(gsl_root_fsolver_brent); gsl_root_fsolver* solver(gsl_root_fsolver_alloc(solverType)); const Real r(findRoot(F, solver, low, high, 1e-18, 1e-12, "GreensFunction2DAbsSym::drawR")); gsl_root_fsolver_free(solver); return r; }
Real getAlpha(size_t n, RealVector::size_type i) const { RealVector& alphaTable( this->alphaTable[n] ); RealVector::size_type oldSize( alphaTable.size() ); if( oldSize <= i ) { alphaTable.resize( i+1 ); unsigned int offset( alphaOffset( n ) ); gsl_root_fsolver* solver( gsl_root_fsolver_alloc(gsl_root_fsolver_brent)); for( RealVector::size_type m( oldSize ); m <= i; ++m ) { alphaTable[m] = alpha_i( m + offset, n, solver ); } gsl_root_fsolver_free( solver ); } return alphaTable[i]; }
/** * Function: get_xvalue_from_tlength * The function computes the x-offset position from the reference point * for a given tracelength in a given beam. * The solution is numerically derived and therefore * does work for any reasonable tracefunction. * * Parameters: * @param actbeam - the beam to compute the x-offset * @param tlength - tracelength * * Returns: * @return xdiff - the x-offset */ double get_xvalue_from_tlength(beam *actbeam, double tlength) { int iter=0; int status; double xdiff=0.0; d_point x_interv; // define and initialize the solver const gsl_root_fsolver_type *T = gsl_root_fsolver_brent; gsl_root_fsolver *s = gsl_root_fsolver_alloc (T); gsl_function F; tlength_pars *tpars; // derive the x-interval from the beam boundaries x_interv = get_xinterv_from_beam(actbeam); // fprintf(stdout, "xpos: %f, ypos: %f\n", x_interv.x, x_interv.y); // allocate and fill the parameters tpars = (tlength_pars *) malloc(sizeof(tlength_pars)); tpars->actbeam = actbeam; tpars->tlength = tlength; // fille the GSL-function F.function = &zero_tlength; F.params = tpars; // set the boundaries for the solver gsl_root_fsolver_set (s, &F, x_interv.x, x_interv.y); // iterate to find the zeropoint do { // increment the iteration counter iter++; // iterate on the solver status = gsl_root_fsolver_iterate (s); // get a new guess from the solver xdiff = gsl_root_fsolver_root (s); // derive and set new boundaries x_interv.x = gsl_root_fsolver_x_lower (s); x_interv.y = gsl_root_fsolver_x_upper (s); // check the accuracy status = gsl_root_test_interval (x_interv.x, x_interv.y, 0, 0.0001); //--------------CAVEAT--------------------------------------- // until March 28th 08 the code, wriongly was: //status = gsl_root_test_interval (x_interv.x, x_interv.x, // 0, 0.0001); // somehow this made no difference..... //----------------------------------------------------------- } // check for the break condition while (status == GSL_CONTINUE && iter < MAX_ITER); // free the memory free(tpars); // free the memory gsl_root_fsolver_free (s); // return the result return xdiff; }