二维和三维向量的旋转
二维向量旋转:
二维向量旋转代码:
[cpp]
#include<iostream>
#include<stdio.h>
#include<math.h>
using namespace std;
#define N 1000
#define eps 1e-8
#define PI acos(-1.0)
struct point{double x,y;}p[N];
int n;
//点q绕(x0,y0) 逆时针旋转ang
point rotate(point q,double x0,double y0,double ang)
{
point ans;
double cosa=cos(ang);
double sina=sin(ang);
double dx=q.x-x0;
double dy=q.y-y0;
ans.x=cosa*dx-sina*dy+x0;
ans.y=sina*dx+cosa*dy+y0;
return ans;
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
point s={1,1};
int i;
for(i=0;i<n;i++)scanf("%lf%lf",&p[i].x,&p[i].y);
for(i=0;i<n;i++)p[i]=rotate(p[i],s.x,s.y,PI/4.0);
for(i=0;i<n;i++)printf("%.2lf %.2lf\n",p[i].x,p[i].y);
}
return 0;
}
/*
in:
4
1 1
2 0
3 1
2 2
out:
1.00 1.00
2.41 1.00
2.41 2.41
1.00 2.41
*/
三维向量旋转:
向量绕任意轴OS(x, y, z)旋转的矩阵:
=⎡⎣⎢⎢⎢⎢⎢⎢⎢⎢⎢⎢⎢x2+(y2+z2)cosθx2+y2+z2yx(1−cosθ)x2+y2+z2+zsinθx2+y2+z2−−−−−−−−−−√zx(1−cosθ)x2+y2+z2−ysinθx2+y2+z2−−−−−−−−−−√xy(1−cosθ)x2+y2+z2−zsinθx2+y2+z2−−−−−−−−−−√y2+(z2+x2)cosθx2+y2+z2zy(1−cosθ)x2+y2+z2+xsinθx2+y2+z2−−−−−−−−−−√xz(1−cosθ)x2+y2+z2+ysinθx2+y2+z2−−−−−−−−−−√yz(1−cosθ)x2+y2+z2−xsinθx2+y2+z2−−−−−−−−−−√z2+(x2+y2)cosθx2+y2+z2⎤⎦⎥⎥⎥⎥⎥⎥⎥⎥⎥⎥⎥
三维向量旋转代码:
[cpp]
#include<iostream>
#include<cstdio>
#include<math.h>
#include<string.h>
#define PI acos(-1.0)
#define eps 1e-8
#define N 1000
using namespace std;
struct point3{double x,y,z;}p[N];
int n;
//求三维空间上一点q绕 向量(x0,y0,z0)正向旋转ang 弧度的点,向量起点在原点
point3 rotate3(point3 q,double x0,double y0,double z0,double ang)
{
double x2=x0*x0;
double y2=y0*y0;
double z2=z0*z0;
double d2=x2+y2+z2;
double d=sqrt(d2);
double sina=sin(ang);
double cosa=cos(ang);
point3 ans;
ans.x=(x2+(y2+z2)*cosa)/d2*q.x
+ (x0*y0*(1-cosa)/d2 - z0*sina/d )* q.y
+ (x0*z0*(1-cosa)/d2+y0*sina/d)*q.z;
ans.y=(y0*x0*(1-cosa)/d2+z0*sina/d)*q.x
+ (y2+(x2+z2)*cosa)/d2* q.y
+ (y0*z0*(1-cosa)/d2-x0*sina/d)*q.z;
ans.z=(z0*x0*(1-cosa)/d2 - y0*sina/d)*q.x
+ (z0*y0*(1-cosa)/d2+x0*sina/d)*q.y
+ (z2+(x2+y2)*cosa)/d2*q.z;
return ans;
}
int main()
{
#ifndef Online_Judge
freopen("in.txt","r",stdin);
#endif
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=0;i<n;i++)scanf("%lf%lf%lf",&p[i].x,&p[i].y,&p[i].z);
double x0=0,y0=0,z0=1;
double ang=PI/4.0;
for(i=0;i<n;i++)p[i]=rotate3(p[i],x0,y0,z0,ang);
for(i=0;i<n;i++)printf("%.8lf %.8lf %.8lf\n",p[i].x,p[i].y,p[i].z);
}
return 0;
}
/*
in:
8
0 0 0
1 -1 0
2 0 0
1 1 0
0 0 1
1 -1 1
2 0 1
1 1 1
out:
0.00000000 0.00000000 0.00000000
1.41421356 -0.00000000 0.00000000
1.41421356 1.41421356 0.00000000
0.00000000 1.41421356 0.00000000
0.00000000 0.00000000 1.00000000
1.41421356 -0.00000000 1.00000000
1.41421356 1.41421356 1.00000000
0.00000000 1.41421356 1.00000000
*/
补充:软件开发 , C++ ,