二维几何基础
浮点数的比较
//符号函数
int sgn(double x)
{
if(fabs(x) < eps) return 0;
else return x<0?-1:1;
}
//浮点数的比较
int cmp(double x,double y)
{
if(fabs(x-y) < eps) return 0;
else return x<y?-1:1;
}
点和向量
struct Point
{
double x,y;
Point(double x,double y):x(x),y(y){}
};
typedef Point Vector;
向量的运算
struct Point
{
double x,y;
Point(double x,double y):x(x),y(y){}
Point operator+(Point a)
{
return Point(x+a.x,y+a.y);
}
Point operator-(Point a)
{
return Point(x-a.x,y-a.y);
}
Point operator*(double k)
{
return Point(x*k,y*k);
}
Point operator/(double k)
{
return Point(x/k,y/k);
}
bool operator==(Point a)
{
return sgn(x-a.x)==0 && sgn(y-a.y)==0;
}
};
typedef Point Vector;
点积和叉积
//点积
double dot(Vector a,Vector b)
{
return a.x*b.x+a.y*b.y;
}
//叉积
double cross(Vector a,Vector b)
{
return a.x*b.y-a.y*b.x;
}
点积的应用
判断\(A\)与\(B\)的夹角是钝角还是锐角。
点积有正负,利用正负号可以判断向量的夹角。
- 若\(dot(A,B)>0\),\(A\)与\(B\)的夹角为锐角
- 若\(dot(A,B)<0\),\(A\)与\(B\)的夹角为钝角
- 若\(dot(A,B)=0\),\(A\)与\(B\)的夹角为直角
//求向量的长度
double len(Vector a)
{
return sqrt(dot(a,a));
}
//求两向量的夹角
double angle(Vector a,Vector b)
{
return acos(dot(a,b)/len(a)/len(b));
}
//两向量构成的平行四边形的有向面积
double area(Point a,Point b,Point c)
{
return cross(b-a,c-a);
}
//向量逆时针旋转角度rad
Vector rotate(Vector a,double rad)
{
return Vector(a.x*cos(rad)-a.y*sin(rad),a.x*sin(rad)+a.y*cos(rad));
}

浙公网安备 33010602011771号