コード例 #1
0
ファイル: quadratic.c プロジェクト: travesteez/CalPolyCPE
int main(void) {
	double a, b, c, x;
	
	a = getDouble('a');
	b = getDouble('b');
	c = getDouble('c');
	
	x = quadratic(a, b, c);
	
	printf("One x-value for this equation is %.3f\n", x);
	
	a = getDouble('a');
	b = getDouble('b');
	c = getDouble('c');
	
	x = quadratic(a, b, c);
	
	printf("One x-value for this equation is %.3f\n", x);
	
	a = getDouble('a');
	b = getDouble('b');
	c = getDouble('c');
	
	x = quadratic(a, b, c);
	
	printf("One x-value for this equation is %.3f\n", x);
	
	return 0;
}
コード例 #2
0
ファイル: problem27.cpp プロジェクト: TexAgg/project_euler
int consecutive_length(int a, int b)
{
    int i = 0;
    
    do
     {
         quadratic(1, a, b, i);
         
         i++;
     }
    while(isPrime(quadratic(1, a, b, i)));
    
    return i;
}
コード例 #3
0
ファイル: cphysics.c プロジェクト: aadarshasubedi/Corange
collision point_collide_edge(vec3 p, vec3 v, vec3 e0, vec3 e1) {

  vec3 x0 = vec3_sub(e0, p);
  vec3 x1 = vec3_sub(e1, p);
  
  vec3 d = vec3_sub(x1, x0);  
  float dlen = vec3_length_sqrd(d);
  float vlen = vec3_length_sqrd(v);
  float xlen = vec3_length_sqrd(x0);
  
  float A = dlen * -vlen + vec3_dot(d, v) * vec3_dot(d, v);
  float B = dlen * 2 * vec3_dot(v, x0) - 2 * vec3_dot(d, v) * vec3_dot(d, x0);
  float C = dlen * - xlen + vec3_dot(d, x0) * vec3_dot(d, x0);
  
  float t0, t1, t;
  if (!quadratic(A, B, C, &t0, &t1)) { return collision_none(); }
  
  if (between_or(t0, 0, 1) && between_or(t1, 0, 1)) { t = min(t0, t1); }
  else if (between_or(t0, 0, 1)) { t = t0; }
  else if (between_or(t1, 0, 1)) { t = t1; } 
  else { return collision_none(); }
  
  float range = (vec3_dot(d, v) * t - vec3_dot(d, x0)) / dlen;
  
  if (!between_or(range, 0, 1)) {
    return collision_none();
  } else {
    vec3 spoint = vec3_add(e0, vec3_mul(d, range));
    return collision_new(t, spoint, vec3_normalize(vec3_sub(p, spoint)));
  }

}
コード例 #4
0
ファイル: cphysics.c プロジェクト: aadarshasubedi/Corange
collision sphere_collide_edge(sphere s, vec3 v, vec3 e0, vec3 e1) {
  
  //Wif (unlikely(!line_outside_sphere(s, e0, e1))) { error("Collision Sphere Inside Mesh Edge!"); }
  
  vec3 x0 = vec3_sub(e0, s.center);
  vec3 x1 = vec3_sub(e1, s.center);
  
  vec3 d = vec3_sub(x1, x0);  
  float dlen = vec3_length_sqrd(d);
  float vlen = vec3_length_sqrd(v);
  float xlen = vec3_length_sqrd(x0);
  
  float A = dlen * -vlen + vec3_dot(d, v) * vec3_dot(d, v);
  float B = dlen * 2 * vec3_dot(v, x0) - 2 * vec3_dot(d, v) * vec3_dot(d, x0);
  float C = dlen * (s.radius * s.radius - xlen) + vec3_dot(d, x0) * vec3_dot(d, x0);
  
  float t0, t1, t;
  if (!quadratic(A, B, C, &t0, &t1)) { return collision_none(); }
  
  if (between_or(t0, 0, 1) && between_or(t1, 0, 1)) { t = min(t0, t1); }
  else if (between_or(t0, 0, 1)) { t = t0; }
  else if (between_or(t1, 0, 1)) { t = t1; } 
  else { return collision_none(); }
  
  float range = (vec3_dot(d, v) * t - vec3_dot(d, x0)) / dlen;
  
  if (!between_or(range, 0, 1)) {
    return collision_none();
  } else {
    vec3 spoint = vec3_add(e0, vec3_mul(d, range));
    return collision_new(t, spoint, vec3_normalize(vec3_sub(s.center, spoint)));
  }
  
}
コード例 #5
0
ファイル: twocirc.c プロジェクト: aahud/harvey
static int
twocircles(double m, double p, double p1, double p2, double *x, double *y)
{
	double a;	/* center of meridian circle, a>0 */
	double b;	/* center of parallel circle, b>0 */
	double t,bb;
	if(m > 0) {
		twocircles(-m,p,p1,p2,x,y);
		*x = -*x;
	} else if(p < 0) {
		twocircles(m,-p,p1,-p2,x,y);
		*y = -*y;
	} else if(p < .01) {
		*x = m;
		t = m/p1;
		*y = p + (p2-p)*t*t;
	} else if(m > -.01) {
		*y = p;
		*x = m - m*p*p;
	} else {
		b = p>=1? 1: p>.99? 0.5*(p+1 + p1*p1/(1-p)):
			0.5*(p*p-p1*p1-p2*p2)/(p-p2);
		a = .5*(m - 1/m);
		t = m*m-p*p+2*(b*p-a*m);
		bb = b*b;
		*x = quadratic(1+a*a/bb, -2*a + a*t/bb,
			t*t/(4*bb) - m*m + 2*a*m);
		*y = (*x*a+t/2)/b;
	}
	return 1;
}		
コード例 #6
0
ファイル: Finite.cpp プロジェクト: 3DPrinterGuy/FreeCAD
	int LineArcIntof(const Span& line, const Span& arc, Point& p0, Point& p1, double t[4]) {
		// inters of line arc
		// solving	x = x0 + dx * t			x = y0 + dy * t
		//			x = xc + R * cos(a)		y = yc + R * sin(a)		for t
		// gives :-  t² (dx² + dy²) + 2t(dx*dx0 + dy*dy0) + (x0-xc)² + (y0-yc)² - R² = 0
		int nRoots;
		Vector2d v0(arc.pc, line.p0);
		Vector2d v1(line.p0, line.p1);
		double s = v1.magnitudesqd();

		p0.ok = p1.ok = false;
		if((nRoots = quadratic(s, 2 * (v0 * v1), v0.magnitudesqd() - arc.radius * arc.radius, t[0], t[1])) != 0) {
			double toler = geoff_geometry::TOLERANCE / sqrt(s);							// calc a parametric tolerance
			if(t[0] > -toler && t[0] < 1 + toler) {
				p0 = v1 * t[0] + line.p0;
				p0.ok = arc.OnSpan(p0, &t[2]);
			}
			if(nRoots == 2) {
				if(t[1] > -toler && t[1] < 1 + toler) {
					p1 = v1 * t[1] + line.p0;
					p1.ok = arc.OnSpan(p1, &t[3]);
				}
			}
			if(!p0.ok && p1.ok) {
				p0 = p1;
				p1.ok = false;
			}
			nRoots = (int)p0.ok + (int)p1.ok;
		}
		return nRoots;
	}
コード例 #7
0
ファイル: transform.cpp プロジェクト: sshukul/MoaiSpriter
void Transform::lerp(const Transform& transform, float t, int spin)
{
    if(transform.curve_type == "quadratic") {
        t = quadratic(0, c1, 1, t);
    } else if(transform.curve_type == "cubic") {
        t = cubic(0, c1, c2, 1, t);
    } else if(transform.curve_type == "quartic") {
        t = quartic(0, c1, c2, c3, 1, t);
    } else if(transform.curve_type == "quintic") {
        t = quintic(0, c1, c2, c3, c4, 1, t);
    }
    
    x = lerp(x, transform.x, t);
    y = lerp(y, transform.y, t);
    alpha = lerp(alpha, transform.alpha, t);
    
    // 'spin' is based on what you are coming from (key1)
    if(spin != 0)
    {
        if(spin > 0 && angle > transform.angle)
            angle = lerp(angle, transform.angle + 360, t);
        else if(spin < 0 && angle < transform.angle)
            angle = lerp(angle, transform.angle - 360, t);
        else
            angle = lerp(angle, transform.angle, t);
    }
    if(angle > 360) {
        angle = angle - 360;
    }
    
    scale_x = lerp(scale_x, transform.scale_x, t);
    scale_y = lerp(scale_y, transform.scale_y, t);
}
コード例 #8
0
ファイル: test_macIIc.c プロジェクト: ajsecord/liblayout
void main(int argc, char *argv[])
{
  gq_args param;
  macopt_args a ;
  double *x ;
  int n , status ;
  double epsilon=0.001 ;

  /* Load up the parameters of the function that you want to optimize */
  printf("============================================================\n");
  printf("= Demonstration program for macoptIIc                      =\n");
  printf("= Solves A x = b by minimizing the function 1/2 xAx - bx   =\n");
  printf("= A must be positive definite (e.g. 2 1 1 2)               =\n");
  printf("\n  Dimension of A (eg 2)?\n");
  inputi(&(param.n));
  n=param.n; 
  param.A=dmatrix(1,n,1,n);
  param.b=dvector(1,n);
  /* the metric! : */
  a.m=dvector(1,n);
  x=dvector(1,n);
  typeindmatrix(param.A,1,n,1,n);
  printf("  b vector?\n");
  typeindvector(param.b,1,n);
  printf("  Initial condition x?\n");
  typeindvector(x,1,n);
  printf("  Metric m?\n");
  typeindvector(a.m,1,n);

  /* Check that the gradient_function is the gradient of the function  */
  /* You don't have to do this, but it is a good idea when debugging ! */
  maccheckgrad (  x , param.n , epsilon , 
		quadratic , (void *)(&param) , 
		vgrad_quadratic , (void *)(&param) , 
		0
		) ;

  /* initialize the arguments of the optimizer */
  macopt_defaults ( &a ) ; 

  /* modify macopt parameters from their default values */
  a.do_newitfunc = 1 ; /* this means that I want to have an auxiliary
			  subroutine executed each iteration of the 
			  optimization */
  a.newitfunc = &state_printer ; /* setting the function to be performed to
				  T_return */
  a.newitfuncarg = (void *)(&param) ;
  a.metric = 1 ; /* we have put in the metric and want to use it */
  a.verbose = 2 ; /* verbosity */
  a.rich = 0 ; /* verbosity */
  
  /* Do an optimization */
  status = macoptIIc ( x , param.n , 
	    vgrad_quadratic , (void *)(&param) , &a
	    ) ;

  printf("(%d) Solution:\n", status);
  quadratic(x,&param);
}
コード例 #9
0
ファイル: quaddie.c プロジェクト: Derfador1/introc
int main(void)
{
	double x = 2.0, y = -3.0, z = 1.0;

	double result = quadratic(x, y, z);

	print_number(result);
}
コード例 #10
0
ファイル: ObjTube.cpp プロジェクト: khutchins/Naive-Raytracer
/*
====================
Tube::intersect
	Computes intersection between the Tube and the ray, and returns itself if 
	it is hit or NULL if it is not along with the point of intersection
====================
*/
SceneObject* Tube::intersect(Ray* r, Point &intersect) {
	Vector dist = this->origin - r->start;

	//norm(dist);
	//norm(r->dir);

	//double a = dot3(r->dir,r->dir);
	//double b = 2 * dot3(r->start - this->origin,r->dir);
	//double c = dot3(r->start - this->origin,r->start - this->origin) - this->radius * this->radius;

	//double disc = discrim(a,b,c);

	////Parallel to tube, does not intersect
	//if(dot3(r->dir,this->up) == 0) return false;
	//else if(disc >= 0) { //Find closest intersection
	//	double discSqrt = sqrt(disc);
	//	double quad;
	//	if (b < 0)	quad = (-b - discSqrt)/2.f;
	//	else quad = (-b + discSqrt)/2.f;

	//	double t0 = quad/a;
	//	double t1 = c/quad;
	//	if(t0 > t1) swap(t0,t1);

	//	double t;
	//	if(t0 < 0 && t1 < 0) return false;
	//	if(t0 < 0) t = t1;
	//	else t = t0;

	//	intersect = r->start + t * r->dir;
	//	return this;
	//}
	//return NULL;
	
	/* 
	Ray: O + V * t
	Cylinder: [this->origin,this->up,this->radius]
	A = this->origin
	O = r->start
	V = r->dir
	*/

	Vector AB = this->up;
	Vector AO = r->start - this->origin;
	Vector AOxAB = AO.cross(AB);
	Vector VxAB = r->dir.cross(AB);
	double ab2 = AB.dot(AB);

	double a = VxAB.dot(VxAB);
	double b = 2 * VxAB.dot(AOxAB);
	double c = AOxAB.dot(AOxAB) - this->radius*this->radius * ab2;

	double t = quadratic(a,b,c);
	if(t < 0) return NULL;

	intersect = r->start + t * r->dir;
	return this;
}
コード例 #11
0
ファイル: test2.cpp プロジェクト: nateware/cpp
int doit(void) {
  float a=1.0, b=-6.0, c=8.0, r1, r2;
  if (quadratic(a, b, c, &r1, &r2)) {
    printf("The two roots are %f and %f\n", r1, r2);
  }
  else {
    printf("No real roots exist");
  }
  return 0;
}
コード例 #12
0
ファイル: main.cpp プロジェクト: oakoak/quadratic-equation
int main()
{
    const int n = 3;
    double coefficients_equation[n];
    double root_equation[n];
    printf("Enter values a, b, c\n");
    scanf( "%lg%lg%lg" , &coefficients_equation[2], &coefficients_equation[1], &coefficients_equation[0] );
    quadratic(coefficients_equation, root_equation);
    print_roots(coefficients_equation, root_equation);
    return 0;
}
コード例 #13
0
ファイル: euler27.c プロジェクト: cranklin/projecteuler
int main (int argc, char *argv[]){
    if(argc == 2){
        int argi = atoi(argv[1]);
        printf("\n%d\n", quadratic(argi));
        return 0;
    }
    else{
        printf("\nUsage: quadratic <integer>\n");
        return 1;
    }
}
コード例 #14
0
ファイル: quadt.c プロジェクト: vni/programming
int main() {
	double a, b, c, root1, root2;

	printf("Enter a, b, c: ");
	scanf("%lf %lf %lf", &a, &b, &c);

	if (quadratic(a, b, c, &root1, &root2))
		printf("roots: %.10g %.10g\n", root1, root2);
	else
		printf("No real roots\n");
	return 0;
}
コード例 #15
0
ファイル: complx.cpp プロジェクト: Quna/mspdev
int main () {
    
    dcomplex a(2, 3);
    dcomplex b(4, 5);
    dcomplex c(6, 7);
    
    std::pair<dcomplex, dcomplex> ans = quadratic(a, b, c);

    std::cout << "Roots are " << ans.first << " and "
              << ans.second   << std::endl;

    return 0;
}
コード例 #16
0
ファイル: code3.c プロジェクト: Sirawit7205/C-CPP-codes
int main()
{
	double a=0,b=5,c=4,x1,x2;
	int check;
	check=quadratic(a,b,c,&x1,&x2);
	if(check==0)
		printf("Error\n");
	else if(check==1)
		printf("1 answer: %.6lf (DBG %.6lf)\n",x1,x2);
	else
		printf("2 answers: %.6lf and %.6lf\n",x1,x2);
	return 0;
}
コード例 #17
0
ファイル: Sphere.cpp プロジェクト: yushroom/RenderFish
bool Sphere::intersect_p(const Ray& r) const
{
	// Transform Ray to object space
	Ray ray;
	(*world_to_object)(r, &ray);

	// Compute quadratic sphere coefficients
	float phi;
	Point phit;
	float A = ray.d.x * ray.d.x + ray.d.y * ray.d.y + ray.d.z * ray.d.z;
	float B = 2 * (ray.d.x * ray.o.x + ray.d.y * ray.o.y + ray.d.z * ray.o.z);
	float C = ray.o.x*ray.o.x + ray.o.y*ray.o.y + ray.o.z*ray.o.z - _radius*_radius;

	// Solve quadratic equation for t values
	float t0, t1;
	if (!quadratic(A, B, C, &t0, &t1))
		return false;

	// Compute intersection distance along ray
	if (t0 > ray.maxt || t1 < ray.mint)
		return false;
	float thit = t0;
	if (t0 < ray.mint) {
		thit = t1;
		if (thit > ray.maxt) return false;
	}

	// Compute sphere hit position and phi
	phit = ray(thit);
	if (phit.x == 0.f && phit.y == 0.f) phit.x = 1e-5f * _radius;
	phi = atan2f(phit.y, phit.x);
	if (phi < 0.) phi += 2.f * M_PI;

	// Test sphere intersection against clipping parameters
	if ((_z_min > -_radius && phit.z < _z_min) ||
		(_z_max <  _radius && phit.z > _z_max) || phi > _phi_max) { // clip t0(t1)
		if (thit == t1) return false;
		if (t1 > ray.maxt) return false;
		thit = t1;
		// Compute sphere hit position and phi
		phit = ray(thit);
		if (phit.x == 0.f && phit.y == 0.f) phit.x = 1e-5f * _radius;
		phi = atan2f(phit.y, phit.x);
		if (phi < 0.) phi += 2.f * M_PI;
		if ((_z_min > -_radius && phit.z < _z_min) ||
			(_z_max <  _radius && phit.z > _z_max) || phi > _phi_max)	// clip t1
			return false;
	}

	return true;
}
コード例 #18
0
ファイル: 27.cpp プロジェクト: kgraney/project_euler
int main()
{
	int max_so_far = 0;
	for(int a=-999; a < 1000; a++) {
		for(int b=-999; b < 1000; b++) {
			int n = 0;
			for(; is_prime_cache(quadratic(a,b,n)); n++);
			if (n > max_so_far) {
				std::cout << a << ", " << b << ", " << n << std::endl;
				max_so_far = n;
			}
		}
	}
	std::cout << max_so_far << std::endl;
	return 0;
}
コード例 #19
0
ファイル: ambcomp.c プロジェクト: NREL/Radiance
/* Compute anisotropic radii and eigenvector directions */
static void
eigenvectors(FVECT uv[2], float ra[2], FVECT hessian[3])
{
	double	hess2[2][2];
	FVECT	a, b;
	double	evalue[2], slope1, xmag1;
	int	i;
					/* project Hessian to sample plane */
	for (i = 3; i--; ) {
		a[i] = DOT(hessian[i], uv[0]);
		b[i] = DOT(hessian[i], uv[1]);
	}
	hess2[0][0] = DOT(uv[0], a);
	hess2[0][1] = DOT(uv[0], b);
	hess2[1][0] = DOT(uv[1], a);
	hess2[1][1] = DOT(uv[1], b);
					/* compute eigenvalue(s) */
	i = quadratic(evalue, 1.0, -hess2[0][0]-hess2[1][1],
			hess2[0][0]*hess2[1][1]-hess2[0][1]*hess2[1][0]);
	if (i == 1)			/* double-root (circle) */
		evalue[1] = evalue[0];
	if (!i || ((evalue[0] = fabs(evalue[0])) <= FTINY*FTINY) |
			((evalue[1] = fabs(evalue[1])) <= FTINY*FTINY) ) {
		ra[0] = ra[1] = maxarad;
		return;
	}
	if (evalue[0] > evalue[1]) {
		ra[0] = sqrt(sqrt(4.0/evalue[0]));
		ra[1] = sqrt(sqrt(4.0/evalue[1]));
		slope1 = evalue[1];
	} else {
		ra[0] = sqrt(sqrt(4.0/evalue[1]));
		ra[1] = sqrt(sqrt(4.0/evalue[0]));
		slope1 = evalue[0];
	}
					/* compute unit eigenvectors */
	if (fabs(hess2[0][1]) <= FTINY)
		return;			/* uv OK as is */
	slope1 = (slope1 - hess2[0][0]) / hess2[0][1];
	xmag1 = sqrt(1.0/(1.0 + slope1*slope1));
	for (i = 3; i--; ) {
		b[i] = xmag1*uv[0][i] + slope1*xmag1*uv[1][i];
		a[i] = slope1*xmag1*uv[0][i] - xmag1*uv[1][i];
	}
	VCOPY(uv[0], a);
	VCOPY(uv[1], b);
}
コード例 #20
0
ファイル: lib_flash.c プロジェクト: JacobBarthelmeh/supercop
int
Flash_verify(unsigned char *data, int length, unsigned char signature[37], Flash_Complete_Key PK)
{
	int i;
	unsigned char in[26];
	unsigned char out[26];
	format_message2(data, length, in);
	quadratic(out,signature,PK->Q,PK->L,PK->C,PK->M);	
	for(i=0;i<26;i++)
	{
		if(in[i]!=out[i])
		{
			return 0;
		}
	}
	return 1;
}
コード例 #21
0
ファイル: cphysics.c プロジェクト: aadarshasubedi/Corange
collision point_collide_sphere(vec3 p, vec3 v, sphere s) {
  
  vec3  o = vec3_sub(p, s.center);
  float A = vec3_dot(v, v);
  float B = 2 * vec3_dot(v, o);
  float C = vec3_dot(o, o) - (s.radius * s.radius);
  
  float t0, t1, t;
  if (!quadratic(A, B, C, &t0, &t1)) { return collision_none(); }
  
  if (between_or(t0, 0, 1) && between_or(t1, 0, 1)) { t = min(t0, t1); }
  else if (between_or(t0, 0, 1)) { t = t0; }
  else if (between_or(t1, 0, 1)) { t = t1; } 
  else { return collision_none(); }
  
  return collision_new(t, p, vec3_normalize(vec3_sub(p, s.center)));
  
}
コード例 #22
0
ファイル: cphysics.c プロジェクト: aadarshasubedi/Corange
collision sphere_collide_point(sphere s, vec3 v, vec3 p) {

  //if (unlikely(!point_outside_sphere(s, p))) { error("Collision Sphere Inside Mesh Vertex!"); }

  vec3  o = vec3_sub(s.center, p);
  float A = vec3_dot(v, v);
  float B = 2 * vec3_dot(v, o);
  float C = vec3_dot(o, o) - (s.radius * s.radius);
  
  float t0, t1, t;
  if (!quadratic(A, B, C, &t0, &t1)) { return collision_none(); }
  
  if (between_or(t0, 0, 1) && between_or(t1, 0, 1)) { t = min(t0, t1); }
  else if (between_or(t0, 0, 1)) { t = t0; }
  else if (between_or(t1, 0, 1)) { t = t1; } 
  else { return collision_none(); }
  
  return collision_new(t, p, vec3_normalize(vec3_sub(s.center, p)));
  
}
コード例 #23
0
int main (void)
{
	int a, b, c;

	float quadratic (int a, int b, int c);

	printf ("This is a quadratic equation\n");
	printf ("ax^2 + bx + c = 0\n");
	printf ("What is the value of a? \n");
	scanf ("%i", &a);
	printf ("What is the value of b? \n");
	scanf ("%i", &b);
	printf ("What is the value of c? \n");
	scanf ("%i", &c);

	quadratic (a,b,c);

	printf ("x1 = %f\n", gX1);
	printf ("x2 = %f\n", gX2);

	return 0;
}
コード例 #24
0
int main()
{

    double a = POISON, b = POISON, c = POISON;
    double x1 = POISON, x2 = POISON;

    printf("This program solves quadratic equation.");
    printf("Write coefficients of quadratic equation(e.g a = 123 b = 321 c = 0.1)\n");

    while (!scanf("a = %lg b = %lg c = %lg", &a, &b, &c))
    {

        while (getchar() != '\n');
        printf("Write correct!\n");
    }


    int count_roots = quadratic(a, b, c, &x1, &x2);

    switch(count_roots)
    {

        case INF_ROOTS:
            printf("All real numbers");
            break;
        case 0:
            printf("No roots");
            break;
        case 1:
            printf("Count of roots: %d\nx = %lg", count_roots, x1);
            break;
        case 2:
            printf("Count of roots: %d\nx1 = %lg x2 = %lg", count_roots, x1, x2);
            break;

    }

    return 0;
}
コード例 #25
0
ファイル: sphere.c プロジェクト: peterhajas/gba_raytracer
roots intersection_with_ray(sphere s, ray r)
{
	// We need r in sphere-coordinates

	ray r_sphere_coordinates;
	matrix s_transform_inverse = inverse_of_matrix(s.transform);
	r_sphere_coordinates.point     = transform_point(s_transform_inverse, r.point);
	r_sphere_coordinates.direction = transform_ray(s_transform_inverse, r.direction);

	vector point_minus_center = subtract_vectors(r_sphere_coordinates.point, s.center);

	float polynomials[3];

	polynomials[2] = square_of_magnitude_of_vector(r_sphere_coordinates.direction);
	polynomials[1] = 2 * dot_product(point_minus_center, r_sphere_coordinates.direction);
	polynomials[0] = square_of_magnitude_of_vector(point_minus_center) - s.radius * s.radius;

	roots quad_roots;

	quad_roots = quadratic(polynomials[2], polynomials[1], polynomials[0]);

	return quad_roots;
}
コード例 #26
0
ファイル: cphysics.c プロジェクト: aadarshasubedi/Corange
collision sphere_collide_sphere(sphere s, vec3 v, sphere s0) {

  //if (unlikely(!sphere_outside_sphere(s, s0))) { error("Collision Sphere Inside Sphere!"); }

  vec3  o = vec3_sub(s.center, s0.center);
  float A = vec3_dot(v, v);
  float B = 2 * vec3_dot(v, o);
  float C = vec3_dot(o, o) - ((s.radius + s0.radius) * (s.radius + s0.radius));
  
  float t0, t1, t;
  if (!quadratic(A, B, C, &t0, &t1)) { return collision_none(); }
  
  if (between_or(t0, 0, 1) && between_or(t1, 0, 1)) { t = min(t0, t1); }
  else if (between_or(t0, 0, 1)) { t = t0; }
  else if (between_or(t1, 0, 1)) { t = t1; } 
  else { return collision_none(); }
  
  vec3 proj = vec3_add(s.center, vec3_mul(v, t));
  vec3 twrd = vec3_normalize(vec3_sub(s0.center, proj));
  vec3 p = vec3_add(proj, vec3_mul(twrd, s.radius));
  
  return collision_new(t, p, vec3_normalize(vec3_sub(s.center, p)));

}
コード例 #27
0
void estimate(const size_t order, const Points &X, const HistogramY &Y,
              const size_t i_min, const size_t i_max, const size_t p_min,
              const size_t p_max, bool haveGap, double &out_bg0,
              double &out_bg1, double &out_bg2, double &out_chisq_red) {
  // Validate input
  if (order > 2)
    throw std::runtime_error("can only estimate up to order=2");
  if (i_min >= i_max) {
    std::stringstream err;
    err << "i_min (" << i_min << ")cannot be larger or equal to i_max ("
        << i_max << ")";
    throw std::runtime_error(err.str());
  }
  if (i_max > X.size()) {
    std::stringstream err;
    err << "i_max  (" << i_max << ") cannot be larger or equal to size of X "
        << X.size() << ")";
    throw std::runtime_error(err.str());
  }
  if (haveGap && p_min >= p_max)
    throw std::runtime_error("p_min cannot larger or equal to p_max");
  // ignore when p-range is outside of i-range

  // set all output parameters to zero
  out_bg0 = 0.;
  out_bg1 = 0.;
  out_bg2 = 0.;
  out_chisq_red = INVALID_CHISQ;

  // accumulate sum
  double sum = 0.0;
  double sumX = 0.0;
  double sumY = 0.0;
  double sumX2 = 0.0;
  double sumXY = 0.0;
  double sumX2Y = 0.0;
  double sumX3 = 0.0;
  double sumX4 = 0.0;
  for (size_t i = i_min; i < i_max; ++i) {
    if (haveGap && i >= p_min && i < p_max)
      continue;
    sum += 1.0;
    sumX += X[i];
    sumX2 += X[i] * X[i];
    sumY += Y[i];
    sumXY += X[i] * Y[i];
    sumX2Y += X[i] * X[i] * Y[i];
    sumX3 += X[i] * X[i] * X[i];
    sumX4 += X[i] * X[i] * X[i] * X[i];
  }

  if (sum == 0.) {
    return;
  }

  // Estimate flat
  double bg0_flat = 0.;
  calcFlatParameters(sum, sumY, bg0_flat);

  // Estimate linear
  double bg0_linear = 0.;
  double bg1_linear = 0.;
  calcLinearParameters(sum, sumX, sumY, sumXY, sumX2, bg0_linear, bg1_linear);

  // Estimate quadratic
  double bg0_quadratic = 0.;
  double bg1_quadratic = 0.;
  double bg2_quadratic = 0.;
  calcQuadraticParameters(sum, sumX, sumY, sumXY, sumX2, sumX2Y, sumX3, sumX4,
                          bg0_quadratic, bg1_quadratic, bg2_quadratic);

  // Setup to calculate the residuals
  double chisq_flat = 0.;
  double chisq_linear = 0.;
  double chisq_quadratic = 0.;
  auto residual_flat = constant(bg0_flat);
  auto residual_linear = linear(bg0_linear, bg1_linear);
  auto residual_quadratic =
      quadratic(bg0_quadratic, bg1_quadratic, bg2_quadratic);
  double num_points = 0.;

  // calculate the chisq - not normalized by the number of points
  for (size_t i = i_min; i < i_max; ++i) {
    if (haveGap && i >= p_min && i < p_max)
      continue;

    num_points += 1.;
    chisq_flat += residual_flat(X[i], Y[i]);
    chisq_linear += residual_linear(X[i], Y[i]);
    chisq_quadratic += residual_quadratic(X[i], Y[i]);
  }

  // convert to <reduced chisq> = chisq / (<number points> - <number
  // parameters>)
  chisq_flat = chisq_flat / (num_points - 1.);
  chisq_linear = chisq_linear / (num_points - 2.);
  chisq_quadratic = chisq_quadratic / (num_points - 3.);

  if (order < 2) {
    chisq_quadratic = BAD_CHISQ;
    if (order < 1) {
      chisq_linear = BAD_CHISQ;
    }
  }

  // choose the right background function to return
  // this is written that lower order polynomial wins in the case of a tie
  if ((chisq_flat <= chisq_linear) && (chisq_flat <= chisq_quadratic)) {
    out_bg0 = bg0_flat;
    out_chisq_red = chisq_flat;
  } else if ((chisq_linear <= chisq_flat) &&
             (chisq_linear <= chisq_quadratic)) {
    out_bg0 = bg0_linear;
    out_bg1 = bg1_linear;
    out_chisq_red = chisq_linear;
  } else {
    out_bg0 = bg0_quadratic;
    out_bg1 = bg1_quadratic;
    out_bg2 = bg2_quadratic;
    out_chisq_red = chisq_quadratic;
  }
}
コード例 #28
0
    void TestRead()
    {
        // WRITE VECTOR
        // create a 10 element petsc vector
        unsigned vec_size = 10u;
        Vec vec=PetscTools::CreateVec(vec_size);
        // calculate the range
        PetscInt petsc_lo, petsc_hi;
        VecGetOwnershipRange(vec, &petsc_lo, &petsc_hi);
        unsigned lo=(unsigned)petsc_lo;
        unsigned hi=(unsigned)petsc_hi;
        // create 20 element petsc vector
        Vec striped;
        VecCreateMPI(PETSC_COMM_WORLD, 2*(hi-lo) , 2*vec_size, &striped);
        // write some values
        double* p_vec;
        VecGetArray(vec, &p_vec);
        double* p_striped;
        VecGetArray(striped, &p_striped);
        for (unsigned global_index=lo; global_index<hi; global_index++)
        {
            unsigned local_index = global_index - lo;
            p_vec[local_index] = local_index*global_index;
            p_striped[2*local_index  ] = local_index;
            p_striped[2*local_index+1] = global_index*global_index;
        }
        VecRestoreArray(vec, &p_vec);
        VecAssemblyBegin(vec);
        VecAssemblyEnd(vec);
        VecRestoreArray(striped, &p_striped);
        VecAssemblyBegin(striped);
        VecAssemblyEnd(striped);

        // READ VECTOR
        DistributedVectorFactory factory(vec);
        DistributedVector distributed_vector = factory.CreateDistributedVector(vec);
        DistributedVector distributed_vector2 = factory.CreateDistributedVector(striped);
        DistributedVector::Stripe linear(distributed_vector2,0);
        DistributedVector::Stripe quadratic(distributed_vector2,1);
        // check the range
        TS_ASSERT_EQUALS(factory.GetProblemSize(), vec_size);
        TS_ASSERT_EQUALS(distributed_vector.Begin().Global,lo);
        TS_ASSERT_EQUALS(distributed_vector.End().Global,hi);
        // read some values
        for (DistributedVector::Iterator index = distributed_vector.Begin();
             index!= distributed_vector.End();
             ++index)
        {
            TS_ASSERT_EQUALS(distributed_vector[index], index.Local*index.Global);
            TS_ASSERT_EQUALS(linear[index], index.Local);
            TS_ASSERT_EQUALS(quadratic[index], index.Global * index.Global);
        }

        // read the 2nd element of the first vector
        if (lo<=2 && 2<hi)
        {
            TS_ASSERT(distributed_vector.IsGlobalIndexLocal(2));
            TS_ASSERT_EQUALS(distributed_vector[2],2*(2-lo));
        }
        else
        {
            TS_ASSERT(!distributed_vector.IsGlobalIndexLocal(2));
            TS_ASSERT_THROWS(distributed_vector[2],DistributedVectorException);
        }

        //read the 3rd element of the other vectors
        if (lo<=3 && 3<hi)
        {
            TS_ASSERT(distributed_vector.IsGlobalIndexLocal(3));
            TS_ASSERT_EQUALS(linear[3],(3-lo));
            TS_ASSERT_EQUALS(quadratic[3],3*3);
        }
        else
        {
            TS_ASSERT(!distributed_vector.IsGlobalIndexLocal(3));
            TS_ASSERT_THROWS(linear[3],DistributedVectorException);
            TS_ASSERT_THROWS(quadratic[3],DistributedVectorException);
        }

        PetscTools::Destroy(vec);
        PetscTools::Destroy(striped);
    }
コード例 #29
0
ファイル: SplineInterpolate.cpp プロジェクト: arocchi/Klampt
void MonotonicAccelInterpolate(const vector<Vector>& pts,vector<GeneralizedCubicBezierCurve>& paths,CSpace* space,GeodesicManifold* manifold)
{
  Assert(pts.size() >= 2);
  
  vector<Vector> tangents(pts.size()),inslopes(pts.size()-1),outslopes(pts.size()-1);
  paths.resize(pts.size()-1);
  for(size_t i=0;i<paths.size();i++) {
    paths[i].x0 = pts[i];
    paths[i].x3 = pts[i+1];
    paths[i].space = space;
    paths[i].manifold = manifold;
  }
  paths[0].x0 = pts[0];
  paths[0].x3 = pts[1];
  if(pts.size() == 2) {
    paths[0].SetSmoothTangents(NULL,NULL);
    return;
  }
  paths[0].SetSmoothTangents(NULL,&pts[2]);
  paths[0].Deriv(0,tangents[0]);
  paths.back().x0 = pts[pts.size()-2];
  paths.back().x3 = pts[pts.size()-1];
  paths.back().SetSmoothTangents(&pts[pts.size()-3],NULL);
  paths.back().Deriv(1,tangents.back());
  for(size_t i=1;i<pts.size();i++) {
    if(!manifold) {
      inslopes[i-1] = pts[i]-pts[i-1];
      outslopes[i-1].setRef(inslopes[i-1]);
    }
    else {
      manifold->InterpolateDeriv(pts[i-1],pts[i],0,inslopes[i-1]);
      manifold->InterpolateDeriv(pts[i],pts[i-1],0,outslopes[i-1]);
      outslopes[i-1].inplaceNegative();
    }
    if(i+1<pts.size()) {
      if(!manifold)
	tangents[i] = (pts[i+1]-pts[i-1])*0.5;
      else {
	Vector n,p;
	manifold->InterpolateDeriv(pts[i],pts[i+1],0,n);
	manifold->InterpolateDeriv(pts[i],pts[i-1],0,p);
	tangents[i] = (n-p)*0.5;
      }
    }
  }
  int n=pts[0].n;
  for(size_t i=0;i<pts.size();i++) {
    if(tangents[i].n != n) printf("%d / %d\n",i,tangents.size());
    Assert(tangents[i].n == n);
  }
  for(size_t i=0;i+1<pts.size();i++) {
    if(i == 1)
      cout<<"Orig tangent 2: "<<tangents[i+1]<<endl;
    for(int j=0;j<n;j++) {
      if(j==0) {
	printf("Segment %d: accel in %g, out %g\n",i,3.0*inslopes[i][j] - tangents[i+1][j]-2*tangents[i][j],2*tangents[i+1][j]+tangents[i][j] - 3.0*outslopes[i][j]);
      }
      if(Sign(3.0*inslopes[i][j] - tangents[i+1][j] - 2*tangents[i][j]) != Sign(2*tangents[i+1][j]+tangents[i][j] - 3.0*outslopes[i][j])) {
	//(3.0*mi - x - 2*t0)*(2*x+t0 - 3.0*mo) = 0
	//(- x + 3.0*mi - 2*t0)*(2*x+t0 - 3.0*mo) = 
	//    -2x^2 + x*(-t0+3mo+6mi-4t0) + (3mi-2t0)(t0-3mo) = 0
	//solve quadratic to set tangents[i+1][j] so one accel becomes
	//nullified
	Real a = -2.0;
	Real b = 6*inslopes[i][j] + 3*outslopes[i][j]-5*tangents[i][j];
	Real c = (3*inslopes[i][j]-2*tangents[i][j])*(tangents[i][j]-3*outslopes[i][j]);
	Real t1,t2;
	int res=quadratic(a,b,c,t1,t2);
	if(res == 0) {
	  if(j==0) 
	    printf("No solution to quadratic %g %g %g\n",a,b,c);
	}
	else {
	  assert(res > 0);
	  if(res == 2) {
	    //pick the closer one to the existing tangent
	    if(Abs(t1 - tangents[i+1][j]) > Abs(t2 - tangents[i+1][j]))
	      t1 = t2;
	  }
	  tangents[i+1][j] = t1;
	  if(j==0) {
	    printf("New accel in %g, out %g\n",3.0*inslopes[i][j] - tangents[i+1][j]-2*tangents[i][j],2*tangents[i+1][j]+tangents[i][j] - 3.0*outslopes[i][j]);
	  }
	}
      }
    }
    if(i == 1)
      cout<<"New tangent 2: "<<tangents[i+1]<<endl;
  }
  for(size_t i=0;i+1<pts.size();i++) {
    paths[i].SetNaturalTangents(tangents[i],tangents[i+1]);
    Vector temp,temp2;
    paths[i].Accel(0,temp);
    paths[i].Accel(1,temp2);
    cout<<"in "<<temp[0]<<" out "<<temp2[0]<<endl;
  }
}
コード例 #30
0
    void TestWrite()
    {
        // WRITE VECTOR

        // Create a 10 element petsc vector
        DistributedVectorFactory factory(10);
        Vec striped = factory.CreateVec(2);
        Vec chunked = factory.CreateVec(2);
        Vec petsc_vec = factory.CreateVec();

        DistributedVector distributed_vector = factory.CreateDistributedVector(petsc_vec);
        DistributedVector distributed_vector_striped = factory.CreateDistributedVector(striped);
        DistributedVector distributed_vector_chunked = factory.CreateDistributedVector(chunked);
        DistributedVector::Stripe linear(distributed_vector_striped, 0);
        DistributedVector::Stripe quadratic(distributed_vector_striped, 1);
        DistributedVector::Chunk linear_chunk(distributed_vector_chunked, 0);
        DistributedVector::Chunk quadratic_chunk(distributed_vector_chunked, 1);

        // Write some values
        for (DistributedVector::Iterator index = distributed_vector.Begin();
             index!= distributed_vector.End();
             ++index)
        {
            distributed_vector[index] =  -(double)(index.Local*index.Global);
            linear[index] =  -1;
            quadratic[index] =  index.Local+1;
            linear_chunk[index] = -1;
            quadratic_chunk[index] =  index.Global+1;
        }

        distributed_vector.Restore();
        distributed_vector_striped.Restore();
        distributed_vector_chunked.Restore();

        // READ VECTOR

        // Calculate my range
        PetscInt petsc_lo, petsc_hi;
        VecGetOwnershipRange(petsc_vec,&petsc_lo,&petsc_hi);
        unsigned lo = (unsigned)petsc_lo;
        unsigned hi = (unsigned)petsc_hi;

        // Read some values
        double* p_striped;
        VecGetArray(striped, &p_striped);
        double* p_chunked;
        VecGetArray(chunked, &p_chunked);
        double* p_vec;
        VecGetArray(petsc_vec, &p_vec);
        for (unsigned global_index=lo; global_index<hi; global_index++)
        {
            unsigned local_index = global_index - lo;
            TS_ASSERT_EQUALS(p_vec[local_index], -(double)local_index*global_index);
            TS_ASSERT_EQUALS(p_striped[2*local_index], -1.0);
            TS_ASSERT_EQUALS(p_striped[2*local_index+1], local_index+1);

            TS_ASSERT_EQUALS(linear[global_index], -1.0);
            TS_ASSERT_EQUALS(quadratic[global_index], local_index+1);

            TS_ASSERT_EQUALS(p_chunked[local_index], -1.0);
            TS_ASSERT_EQUALS(p_chunked[ (hi - lo) + local_index], global_index+1);

            TS_ASSERT_EQUALS(linear_chunk[global_index], -1.0);
            TS_ASSERT_EQUALS(quadratic_chunk[global_index], global_index+1);
        }

        // Read item 2 from the distributed vectors (for coverage)
        if (lo<=2 && 2<hi)
        {
            TS_ASSERT(distributed_vector.IsGlobalIndexLocal(2));
            TS_ASSERT_EQUALS(linear[2], -1.0);
            TS_ASSERT_EQUALS(quadratic[2], 3.0 - lo);
            TS_ASSERT_EQUALS(linear_chunk[2], -1.0);
            TS_ASSERT_EQUALS(quadratic_chunk[2], 3.0);
        }
        else
        {
            TS_ASSERT(!distributed_vector.IsGlobalIndexLocal(2));
            TS_ASSERT_THROWS(linear[2],DistributedVectorException);
            TS_ASSERT_THROWS(linear_chunk[2],DistributedVectorException);
        }

        PetscTools::Destroy(petsc_vec);
        PetscTools::Destroy(striped);
        PetscTools::Destroy(chunked);
    }