Example #1
0
int main(void)
{
  roots(1,1,1);
  roots(1,2,1);
  roots(1,-3,2);
  return 0;
}
void
find_self_intersections(std::vector<std::pair<double, double> > &xs,
                        D2<SBasis> const & A) {
    vector<double> dr = roots(derivative(A[X]));
    {
        vector<double> dyr = roots(derivative(A[Y]));
        dr.insert(dr.begin(), dyr.begin(), dyr.end());
    }
    dr.push_back(0);
    dr.push_back(1);
    // We want to be sure that we have no empty segments
    sort(dr.begin(), dr.end());
    vector<double>::iterator new_end = unique(dr.begin(), dr.end());
    dr.resize( new_end - dr.begin() );

    vector<vector<Point> > pieces;
    {
        vector<Point> in, l, r;
        sbasis_to_bezier(in, A);
        for(unsigned i = 0; i < dr.size()-1; i++) {
            split(in, (dr[i+1]-dr[i]) / (1 - dr[i]), l, r);
            pieces.push_back(l);
            in = r;
        }
    }

    for(unsigned i = 0; i < dr.size()-1; i++) {
        for(unsigned j = i+1; j < dr.size()-1; j++) {
            std::vector<std::pair<double, double> > section;
            
            find_intersections( section, pieces[i], pieces[j]);
            for(unsigned k = 0; k < section.size(); k++) {
                double l = section[k].first;
                double r = section[k].second;
// XXX: This condition will prune out false positives, but it might create some false negatives.  Todo: Confirm it is correct.
                if(j == i+1)
                    //if((l == 1) && (r == 0))
                    if( ( l > 1-1e-4 ) && (r < 1e-4) )//FIXME: what precision should be used here???
                        continue;
                xs.push_back(std::make_pair((1-l)*dr[i] + l*dr[i+1],
                                                (1-r)*dr[j] + r*dr[j+1]));
            }
        }
    }

    // Because i is in order, xs should be roughly already in order?
    //sort(xs.begin(), xs.end());
    //unique(xs.begin(), xs.end());
}
Example #3
0
 Z3_ast_vector Z3_API Z3_algebraic_roots(Z3_context c, Z3_ast p, unsigned n, Z3_ast a[]) {
     Z3_TRY;
     LOG_Z3_algebraic_roots(c, p, n, a);
     RESET_ERROR_CODE();
     polynomial::manager & pm = mk_c(c)->pm();
     polynomial_ref _p(pm);
     polynomial::scoped_numeral d(pm.m());
     expr2polynomial converter(mk_c(c)->m(), pm, 0, true);
     if (!converter.to_polynomial(to_expr(p), _p, d) ||
         static_cast<unsigned>(max_var(_p)) >= n + 1) {
         SET_ERROR_CODE(Z3_INVALID_ARG);
         return 0;
     }
     algebraic_numbers::manager & _am = am(c);
     scoped_anum_vector as(_am);
     if (!to_anum_vector(c, n, a, as)) {
         SET_ERROR_CODE(Z3_INVALID_ARG);
         return 0;
     }
     scoped_anum_vector roots(_am);
     {
         cancel_eh<algebraic_numbers::manager> eh(_am);
         api::context::set_interruptable si(*(mk_c(c)), eh);
         scoped_timer timer(mk_c(c)->params().m_timeout, &eh);
         vector_var2anum v2a(as);
         _am.isolate_roots(_p, v2a, roots);
     }
     Z3_ast_vector_ref* result = alloc(Z3_ast_vector_ref, mk_c(c)->m());
     mk_c(c)->save_object(result);
     for (unsigned i = 0; i < roots.size(); i++) {
         result->m_ast_vector.push_back(au(c).mk_numeral(roots.get(i), false));
     }
     RETURN_Z3(of_ast_vector(result));
     Z3_CATCH_RETURN(0);
 }
Example #4
0
  bool ArModel::check_stationary(const Vec &phi){
    // The process is stationary if the roots of the polynomial
    //
    // 1 - phi[0]*z - ... - phi[p-1]*z^p.
    //
    // all lie outside the unit circle.  We can do that by explicitly
    // finding and checking the roots, but that's kind of expensive.
    // Before doing that we can do a quick check to see if the
    // coefficients are within a loose bound.
    //
    // Based on Rouche's theorem:
    // http://en.wikipedia.org/wiki/Properties_of_polynomial_roots#Based_on_the_Rouch.C3.A9_theorem
    // All the roots will be at least 1 in absolute value as long as
    // sum(abs(phi)) < 1.
    if(phi.abs_norm() < 1) return true;

    // If that didn't work then we're stuck finding roots.
    // TODO(stevescott): Really we just need to check the smallest
    // root.  If we had a cheap way of finding just the smallest root
    // then that would be more efficient than finding them all.
    Vector coefficients = concat(1, -1 * phi);
    Polynomial polynomial(coefficients);
    std::vector<std::complex<double> > roots(polynomial.roots());
    for (int i = 0; i < roots.size(); ++i) {
      if (abs(roots[i]) <= 1) return false;
    }
    return true;
  }
Example #5
0
/** Return the sign of the two functions pointwise.
 \param f function
*/
Piecewise<SBasis> signSb(Piecewise<SBasis> const &f){
    Piecewise<SBasis> sign=partition(f,roots(f));
    for (unsigned i=0; i<sign.size(); i++){
        sign.segs[i] = (sign.segs[i](.5)<0)? Linear(-1.):Linear(1.);
    }
    return sign;
}
Example #6
0
/** Return the absolute value of a function pointwise.
 \param f function
*/
Piecewise<SBasis> abs(Piecewise<SBasis> const &f){
    Piecewise<SBasis> absf=partition(f,roots(f));
    for (unsigned i=0; i<absf.size(); i++){
        if (absf.segs[i](.5)<0) absf.segs[i]*=-1;
    }
    return absf;
}
Example #7
0
/* return Bs: if r a root of sigma_i(P), |r| < Bs[i] */
static GEN
nf_root_bounds(GEN P, GEN T)
{
  long lR, i, j, l, prec;
  GEN Ps, R, V, nf;

  if (RgX_is_rational(P)) return logmax_modulus_bound(P);
  T = get_nfpol(T, &nf);

  P = Q_primpart(P);
  prec = ZXY_get_prec(P);
  l = lg(P);
  if (nf && nfgetprec(nf) >= prec)
    R = gel(nf,6);
  else
    R = roots(T, prec);
  lR = lg(R);
  V = cgetg(lR, t_VEC);
  Ps = cgetg(l, t_POL); /* sigma (P) */
  Ps[1] = P[1];
  for (j=1; j<lg(R); j++)
  {
    GEN r = gel(R,j);
    for (i=2; i<l; i++) gel(Ps,i) = poleval(gel(P,i), r);
    gel(V,j) = logmax_modulus_bound(Ps);
  }
  return V;
}
Example #8
0
 vector<int> numIslands2(int m, int n, vector<pair<int, int>>& positions) {
     vector<int> ret;
     if(m<=0 || n <=0) return ret;
     
     int numIsland = 0; //count the number of islands
     vector<int> roots(m*n, -1); //one island = one tree
     vector<vector<int>> dirs = {{-1,0},{1,0},{0,1},{0,-1}}; //four directions
     
     for(pair<int,int> p:positions){
         int root = n * p.first + p.second;
         roots[root] = root; //add a new island
         numIsland++;
         
         for(vector<int> d:dirs){
             int x = p.first + d[0];
             int y = p.second + d[1];
             int newId = n * x + y;
             if(x<0 || x>=m || y<0 || y>=n || roots[newId]==-1){
                 continue;
             }
             
             //not -1, there is already an island
             int rootId = findIsland(roots, newId);
             if(root != rootId){
                 roots[root] = rootId; 
                 root = rootId; //union this to neighbor island
                 numIsland--;
             }
         }
         ret.push_back(numIsland);
     }
     return ret;
 }
	/**
	 * @param connections given a list of connections include two cities and cost
	 * @return a list of connections from results
	 */
	vector<Connection> lowestCost(vector<Connection>& connections) {
		sort(connections.begin(), connections.end(), Comp());
		unordered_map<string, int> labels;
		int n = 0;
		for (const auto & i : connections) {
			if (!labels.count(i.city1)) {
				labels[i.city1] = n;
				++n;
			}
			if (!labels.count(i.city2)) {
				labels[i.city2] = n;
				++n;
			}
		}
		vector<int> roots(n);
		iota(roots.begin(), roots.end(), 0);
		vector<Connection> result;
		for (const auto & i : connections) {
			int label1 = labels[i.city1], label2 = labels[i.city2];
			int root1 = getRoot(roots, label1), root2 = getRoot(roots, label2);
			if (root1 != root2) {
				roots[root1] = root2;
				--n;
				result.push_back(i);
			}
		}
		return n == 1 ? result : vector<Connection>();
	}
    vector<CoeffT> Polynomial<CoeffT>::roots(size_t num_iterations, CoeffT ztol) const
    {
      assert(c.size() >= 1);
      size_t n = c.size() - 1;

      // initial guess
      vector<complex<CoeffT>> z0(n);
      for (size_t j = 0; j < n; j++) {
        z0[j] = pow(complex<double>(0.4, 0.9), j);
      }

      // durand-kerner-weierstrass iterations
      Polynomial<CoeffT> p = this->normalize();
      for (size_t k = 0; k < num_iterations; k++) {
        complex<CoeffT> num, den;
        for (size_t i = 0; i < n; i++) {
          num = p.evaluate(z0[i]);
          den = 1.0;
          for (size_t j = 0; j < n; j++) {
            if (j == i) { continue; }
            den = den * (z0[i] - z0[j]);
          }
          z0[i] = z0[i] - num / den;
        }
      }

      vector<CoeffT> roots(n);
      for (size_t j = 0; j < n; j++) {
        roots[j] = abs(z0[j]) < ztol ? 0.0 : real(z0[j]);
      }

      sort(roots.begin(), roots.end());
      return roots;
    }
Example #11
0
static void tst_isolate_roots(polynomial_ref const & p, anum_manager & am,
                              polynomial::var x0, anum const & v0, polynomial::var x1, anum const & v1, polynomial::var x2, anum const & v2) {
    polynomial::simple_var2value<anum_manager> x2v(am);
    x2v.push_back(x0, v0);
    x2v.push_back(x1, v1);
    x2v.push_back(x2, v2);
    std::cout << "--------------\n";
    std::cout << "p: " << p << "\n";
    std::cout << "x0 -> "; am.display_root(std::cout, v0); std::cout << "\n";
    std::cout << "x1 -> "; am.display_root(std::cout, v1); std::cout << "\n";
    std::cout << "x2 -> "; am.display_root(std::cout, v2); std::cout << "\n";
    scoped_anum_vector roots(am);
    svector<int> signs;
    am.isolate_roots(p, x2v, roots, signs);
    SASSERT(roots.size() + 1 == signs.size());
    std::cout << "roots:\n";
    for (unsigned i = 0; i < roots.size(); i++) {
        am.display_root(std::cout, roots[i]); std::cout << " "; am.display_decimal(std::cout, roots[i]); std::cout << "\n";
    }
    std::cout << "signs:\n";
    for (unsigned i = 0; i < signs.size(); i++) {
        if (i > 0)
            std::cout << " 0 ";
        if (signs[i] < 0) std::cout << "-";
        else if (signs[i] == 0) std::cout << "0";
        else std::cout << "+";
    }
    std::cout << "\n";
}
Example #12
0
/** Return the greater of the two functions pointwise.
 \param f, g two functions
*/
Piecewise<SBasis> max(Piecewise<SBasis> const &f, Piecewise<SBasis> const &g){
    Piecewise<SBasis> max=partition(f,roots(f-g));
    Piecewise<SBasis> gg =partition(g,max.cuts);
    max = partition(max,gg.cuts);
    for (unsigned i=0; i<max.size(); i++){
        if (max.segs[i](.5)<gg.segs[i](.5)) max.segs[i]=gg.segs[i];
    }
    return max;
}
Example #13
0
Interval bounds_exact(SBasis const &a) {
    Interval result = Interval(a.at0(), a.at1());
    SBasis df = derivative(a);
    vector<double>extrema = roots(df);
    for (unsigned i=0; i<extrema.size(); i++){
        result.extendTo(a(extrema[i]));
    }
    return result;
}
Example #14
0
CTEST(roots, all_zero) {
	float a = 0;
	float b = 0;
	float c = 0;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	ASSERT_EQUAL(x, 0);
}
Example #15
0
CTEST(roots, a_and_b_zero) {
	float a = 0;
	float b = 0;
	float c = 5;

	float x1, x2;
	int x = roots(a, b, c, &x1, &x2);

	ASSERT_EQUAL(x, 0);
}
Example #16
0
CTEST(roots, discr_negative) {
	float a = 2;
	float b = 1;
	float c = 4;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	ASSERT_EQUAL(x, 0);
}
Example #17
0
void Foam::multiSolver::setUpParallel()
{
    if (Pstream::master())
    {
        fileNameList roots(Pstream::nProcs());
        
        roots[0] = multiDictRegistry_.rootPath();
        manageLocalRoot_ = true;
        
        // Receive from slaves
        for
        (
            int slave=Pstream::firstSlave();
            slave<=Pstream::lastSlave();
            slave++
        )
        {
            IPstream fromSlave(Pstream::blocking, slave);
            roots[slave] = fileName(fromSlave);
        }
        
        // Distribute
        for
        (
            int slave=Pstream::firstSlave();
            slave<=Pstream::lastSlave();
            slave++
        )
        {
            OPstream toSlave(Pstream::blocking, slave);
            if (roots[slave] != roots[slave - 1])
            {
                toSlave << true;
            }
            else
            {
                toSlave << false;
            }
        }
    }
    else
    {
        // Send to master
        {
            OPstream toMaster(Pstream::blocking, Pstream::masterNo());
            toMaster << fileName(multiDictRegistry_.rootPath());
        }
        // Receive from master
        {
            IPstream fromMaster(Pstream::blocking, Pstream::masterNo());
            manageLocalRoot_ = readBool(fromMaster);
        }
    }
}
Example #18
0
int main()
 {
float a,b,c;
struct quad r;
printf("enter the coefficients of the quadratic equation a,b and c");
scanf("%f%f%f",&a,&b,&c);
 roots(a,b,c,&r);
printf("Solution:Root 1 \n The real part of root1 is %f \n",r.r1.real);
printf(" The imaginary part of root1 is %f \n",r.r1.img);
 printf("Root 2  \n The real part of root2 is %f \n",r.r2.real);
printf("The imaginary part of root2 is %f \n",r.r2.img);
return 5;
}
Example #19
0
std::vector<std::vector<double> > multi_roots(SBasis const &f,
                                      std::vector<double> const &levels,
                                      double htol,
                                      double vtol,
                                      double a,
                                      double b){

    std::vector<std::vector<double> > roots(levels.size(), std::vector<double>());

    SBasis df=derivative(f);
    multi_roots_internal(f,df,levels,roots,htol,vtol,a,f(a),b,f(b));  

    return(roots);
}
int main(int argc, const char * argv[]) {
    /* declare variables */
    float x;
    float roots(float x);
    float results;
    x = atof(argv[1]);

    results = roots(x);

    /* print to screen */
    printf("For x = %f the value of the polynomial is %f\n", x, results);

    return 0;
}
      void TestLoad::testLoadEngine()
      {
        std::string content(
          "<?xml version=\"1.0\"?>\n"
            "<model>\n"
              "<object id=\"1\">\n"
                "<Engine>\n"
                  "<ObjectReference id=\"2\" name=\"controler\"/>\n"
                  "<Force x=\"1\" y=\"0\" z=\"0\" unit=\"Newton\"/>\n"
                "</Engine>\n"
              "</object>\n"
              "<object id=\"2\">\n"
                "<EngineControler>\n"
                  "<ObjectReference id=\"32\" name=\"throttle\"/>\n"
                "</EngineControler>\n"
              "</object>\n"
              "<object id=\"3\">\n"
                "<Throttle y=\"0\"/>\n"
              "</object>\n"
            "</model>\n") ;
        std::auto_ptr<Kernel::XMLReader> reader(Kernel::XMLReader::getStringReader(content)) ;
        std::auto_ptr<Kernel::Model> model(new Kernel::Model("TestLoad::testLoadEngine")) ;          
        reader->read(model.get()) ;

        std::set<Kernel::Object*> roots(model->getRoots()) ;
        CPPUNIT_ASSERT(roots.size() == 3) ;
        
        bool exist_engine = false ;
        bool exist_engine_controler = false ;
        bool exist_throttle = false ;
        
        for (std::set<Kernel::Object*>::iterator current = roots.begin() ;
             current != roots.end() ;
             ++current)
        {
          Kernel::Object* object = *current ;
          
          if (object->getTrait<Engine>())
            exist_engine = true ;
          if (object->getTrait<EngineControler>())
            exist_engine_controler = true ;
          if (object->getTrait<Throttle>())
            exist_throttle = true ;
        }
          
        CPPUNIT_ASSERT(exist_engine) ;
        CPPUNIT_ASSERT(exist_engine_controler) ;
        CPPUNIT_ASSERT(exist_throttle) ;
      }
Example #22
0
CTEST(roots, b_zero) {
	float a = 1;
	float b = 0;
	float c = -16;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	float expected_x1 = 4;
	float expected_x2 = -4;

	ASSERT_EQUAL(x, 2);
	ASSERT_EQUAL(expected_x1, x1);
	ASSERT_EQUAL(expected_x2, x2);
}
Example #23
0
CTEST(roots, b_and_c_zero) {
	float a = 81;
	float b = 0;
	float c = 0;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	float expected_x1 = 0;
	float expected_x2 = 0;

	ASSERT_EQUAL(x, 1);
	ASSERT_EQUAL(expected_x1, x1);
	ASSERT_EQUAL(expected_x2, x2);
}
Example #24
0
CTEST(roots, a_is_zero) {
        float a = 0;
        float b = 9;
        float c = 18;

        float x1, x2;
        int x = roots(a, b, c, &x1, &x2);

        float expected_x1 = -2;
        float expected_x2 = -2;

        ASSERT_EQUAL(x, 1);
        ASSERT_EQUAL(expected_x1, x1);
        ASSERT_EQUAL(expected_x2, x2);
}
Example #25
0
        //! @{
        virtual void compute_nodes() override
        {
          this->nodes = vector<precision>(this->num_nodes, precision(0.0));
          auto l   = Polynomial<precision>::legendre(this->num_nodes);
          auto lm1 = Polynomial<precision>::legendre(this->num_nodes - 1);

          for (size_t i = 0; i < this->num_nodes; i++) {
            l[i] += lm1[i];
          }
          auto roots = l.roots();
          for (size_t j = 1; j < this->num_nodes; j++) {
            this->nodes[j - 1] = 0.5 * (1.0 - roots[this->num_nodes - j]);
          }
          this->nodes.back() = 1.0;
        }
Example #26
0
CTEST(roots, c_zero) {
	float a = 1;
	float b = 9;
	float c = 0;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	float expected_x1 = 0;
	float expected_x2 = -9;

	ASSERT_EQUAL(x, 2);
	ASSERT_EQUAL(expected_x1, x1);
	ASSERT_EQUAL(expected_x2, x2);
}
Example #27
0
CTEST(roots, all_negative) {
	float a = -2;
	float b = -4;
	float c = -2;

	float x1, x2;
	float x = roots(a, b, c, &x1, &x2);

	float expected_x1 = -1;
	float expected_x2 = -1;

	ASSERT_EQUAL(x, 1);
	ASSERT_EQUAL(expected_x1, x1);
	ASSERT_EQUAL(expected_x2, x2);
}
Example #28
0
void
eval_roots(void)
{
	// A == B -> A - B

	p2 = cadr(p1);

	if (car(p2) == symbol(SETQ) || car(p2) == symbol(TESTEQ)) {
		push(cadr(p2));
		eval();
		push(caddr(p2));
		eval();
		subtract();
	} else {
		push(p2);
		eval();
		p2 = pop();
		if (car(p2) == symbol(SETQ) || car(p2) == symbol(TESTEQ)) {
			push(cadr(p2));
			eval();
			push(caddr(p2));
			eval();
			subtract();
		} else
			push(p2);
	}

	// 2nd arg, x

	push(caddr(p1));
	eval();
	p2 = pop();
	if (p2 == symbol(NIL))
		guess();
	else
		push(p2);

	p2 = pop();
	p1 = pop();

	if (!ispoly(p1, p2))
		stop("roots: 1st argument is not a polynomial");

	push(p1);
	push(p2);

	roots();
}
 int countComponents(int n, vector<pair<int, int>>& edges) {
     vector<int> roots(n);
     for (int i = 0; i < n; ++i) {
         roots[i] = i;
     }
     
     for (auto& edge : edges) {
         int x = find(roots, edge.first);
         int y = find(roots, edge.second);
         if (x != y) {
             roots[x] = y;
             n--;
         }
     }
     return n;
 }
      void TestLoad::testLoadComputer()
      {
        std::string content(
          "<?xml version=\"1.0\"?>\n"
            "<model>\n"
              "<object id=\"1\">\n"
                "<Computer/>\n"
              "</object>\n"
            "</model>\n") ;
        std::auto_ptr<Kernel::XMLReader> reader(Kernel::XMLReader::getStringReader(content)) ;
        std::auto_ptr<Kernel::Model> model(new Kernel::Model("TestLoad::testLoadComputer")) ;          
        reader->read(model.get()) ;

        std::set<Kernel::Object*> roots(model->getRoots()) ;
        CPPUNIT_ASSERT(roots.size() == 1) ;
        Kernel::Object* root = *roots.begin() ;
        CPPUNIT_ASSERT(root->getTrait<Computer>()) ;
      }