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(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; }
//---------------------------------------------------------------------------- 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; }
/* 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; }
RatesEM(int ntrees, int nspecies, int nrates, int *gene_sizes, float **lengths, float *times, float *sp_alpha, float *sp_beta, float gene_alpha, float gene_beta) : ntrees(ntrees), nspecies(nspecies), gene_sizes(gene_sizes), lengths(lengths), times(times), sp_alpha(sp_alpha), sp_beta(sp_beta), gene_alpha(gene_alpha), gene_beta(gene_beta), nrates(nrates), gtab(ntrees, nrates), pgtab(ntrees, nrates) { // allocate gene rate optimizer sol_gene_rate = gsl_root_fsolver_alloc(gsl_root_fsolver_brent); // setup optimizer for gene rates opt_gene_rate.function = &gene_rate_f; opt_gene_rate.params = this; // setup optimizer for species rates const int ndim = 2; sol_sp_rate = gsl_multimin_fdfminimizer_alloc( gsl_multimin_fdfminimizer_vector_bfgs2, ndim); opt_sp_rate.f = &sp_rate_f; opt_sp_rate.df = &sp_rate_df; opt_sp_rate.fdf = &sp_rate_fdf; opt_sp_rate.n = ndim; opt_sp_rate.params = this; }
//_______________________________________________________________________________________________________________________ /// /// \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; }
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; }
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; }
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; }
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); }
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; }
/// 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; }
/* 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; }
int UnidimensionalRootFinder(gsl_function *F, double lower_bound, double upper_bound, double abs_error, double rel_error, int max_iterations, double *return_result) { const gsl_root_fsolver_type * T = gsl_root_fsolver_bisection; gsl_root_fsolver * s = gsl_root_fsolver_alloc(T); // Test if the limits straddle the root, // if they don't, we will return -1. if (GSL_SIGN(GSL_FN_EVAL(F, lower_bound)) == GSL_SIGN(GSL_FN_EVAL(F, upper_bound))) return -1; gsl_root_fsolver_set(s, F, lower_bound, upper_bound); int i = 0; double x_lower; double x_upper; do{ i++; int status = gsl_root_fsolver_iterate(s); if (status != GSL_SUCCESS){ printf("ERROR: No solution to the gap equation was found!\n"); exit(EXIT_FAILURE); } x_lower = gsl_root_fsolver_x_lower(s); x_upper = gsl_root_fsolver_x_upper(s); } while(GSL_CONTINUE == gsl_root_test_interval(x_lower, x_upper, abs_error, rel_error) && i <= max_iterations); double result = gsl_root_fsolver_root(s); void gsl_root_fsolver_free(gsl_root_fsolver * S); *return_result = result; return 0; }
int Solver1d::Main () { fsolver_type=gsl_root_fsolver_brent; s = gsl_root_fsolver_alloc (fsolver_type); gsl_root_fsolver_set (s, &F, x_lo, x_hi); do { iter++; status = gsl_root_fsolver_iterate (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); return status; }
/// 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; }
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 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 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 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. }
static VALUE rb_gsl_fsolver_new(VALUE klass, VALUE t) { gsl_root_fsolver *s = NULL; const gsl_root_fsolver_type *T; char name[32]; switch (TYPE(t)) { case T_STRING: strcpy(name, STR2CSTR(t)); if (!str_tail_grep(name, "bisection")) { T = gsl_root_fsolver_bisection; } else if (!str_tail_grep(name, "falsepos")) { T = gsl_root_fsolver_falsepos; } else if (!str_tail_grep(name, "brent")) { T = gsl_root_fsolver_brent; } else { rb_raise(rb_eTypeError, "type must be \"bisection\" or \"falsepos\", or \"brent\"."); } break; case T_FIXNUM: switch (FIX2INT(t)) { case GSL_ROOT_FSOLVER_BISECTION: T = gsl_root_fsolver_bisection; break; case GSL_ROOT_FSOLVER_FALSEPOS: T = gsl_root_fsolver_falsepos; break; case GSL_ROOT_FSOLVER_BRENT: T = gsl_root_fsolver_brent; break; default: rb_raise(rb_eTypeError, "type must be BISECTION or FALSEPOS, or BRENT."); break; } break; default: rb_raise(rb_eTypeError, "wrong argument type %s (String or Fixnum expected)", rb_class2name(CLASS_OF(t))); break; } s = gsl_root_fsolver_alloc(T); return Data_Wrap_Struct(klass, 0, gsl_root_fsolver_free, s); }
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; }
int main () { int status; int iterations = 0, max_iterations = 100; gsl_root_fsolver *s; double r = 0, r_expected = sqrt (5.0); double x_lower x = 0.0, x_upper = 5.0; gsl_function F; struct quadratic_params params = {1.0, 0.0, -5.0}; F.function = &quadratic; F.params = ¶ms; s = gsl_root_fsolver_alloc (gsl_root_fsolver_bisection); gsl_root_fsolver_set (s, &F, x); printf ("using %s method\n", gsl_root_fsolver_name (s)); printf ("%5s [%9s, %9s] %9s %9s %10s %9s\n", "iter", "lower", "upper", "root", "actual", "err", "err(est)"); do { iterations++; status = gsl_root_fsolver_iterate (s); r = gsl_root_fsolver_root (s); x_lower = gsl_root_fsolver_x_lower (s); x_upper = gsl_root_fsolver_x_upper (s); status = gsl_root_test_interval (x, 0, 0.001); if (status == GSL_SUCCESS) printf ("Converged:\n"); printf ("%5d [%.7f, %.7f] %.7f %.7f %+.7f %.7f\n", iterations, x_lower, x_upper, r, r_expected, r - r_expected, x_upper - x_lower); } while (status == GSL_CONTINUE && iterations < max_iterations); }
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); }
Chevalier::Chevalier(void) { //constant parsec_in_cm = 3.085678e+18; //parsec in cm parsec_in_km = 3.085678e+13; //parsec in km msun_in_g = 1.988920e+33; //msun in g year_in_sec = 3.155760e+07; //year in s //define the GSL root solver to use grsolve_T = gsl_root_fsolver_brent; grsolve = gsl_root_fsolver_alloc(grsolve_T); //set a default model double M_dot_in = 1.0; //Mass input in Msun/yr double E_dot_in = 43.0; //log E in erg / s double gamma_in = 5./3.; //gamma = 5/3 double R_in = 200.; //parsec //set the mode parameters SetChevalier(M_dot_in, E_dot_in, gamma_in, R_in); }
// 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; }
CAMLprim value ml_gsl_root_fsolver_alloc(value t) { struct callback_params *params; gsl_root_fsolver *s; s = gsl_root_fsolver_alloc(Fsolvertype_val(t)); params=stat_alloc(sizeof(*params)); { CAMLparam0(); CAMLlocal1(res); res=alloc_small(2, Abstract_tag); Field(res, 0) = (value)s; Field(res, 1) = (value)params; params->gslfun.gf.function = &gslfun_callback; params->gslfun.gf.params = params; params->closure = Val_unit; params->dbl = Val_unit; register_global_root(&(params->closure)); CAMLreturn(res); } }
/** * 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; }