2009年10月21日水曜日
ベクトル
【サンプルソース】
public class Vector
{
float x;
float y;
float z;
Vector(float x,float y,float z)
{
this.x = x;
this.y = y;
this.z = z;
}
//加算
public Vector add(Vector v){
return
new Vector(
this.x + v.x,
this.y + v.y,
this.z + v.z
);
}
//ベクトルを反転する
public Vector getInvert()
{
return
new Vector(
-x,
-y,
-z
);
}
// 倍
public Vector times(float n){
return
new Vector(
n * this.x,
n * this.y,
n * this.z
);
}
//単位ベクトル化
Vector unit()
{
//単位ベクトルとは長さが1のベクトルのこと。
float len = (float)(1 / len());
return new Vector(
x *= len,
y *= len,
z *= len
);
}
// 長さ
float len()
{
return (float)Math.sqrt(x*x + y*y + z*z);
}
//内積
static float getDot(Vector a,Vector b)
{
//内積を取るとベクトルとベクトルのなす角度が求まる。
return (
a.x * b.x +
a.y * b.y +
a.z * b.z
);
}
//外積
static Vector getCross(Vector a,Vector b)
{
//外積は主に面に垂直な法線ベクトルを求めるために使用する。
return new Vector(
a.y * b.z - a.z * b.y,
a.z * b.x - a.x * b.z,
a.x * b.y - a.y * b.x
);
}
public String toString(){
StringBuffer sbf = new StringBuffer();
// sbf.append("(x,y,z )>>>(" );
sbf.append("(" );
sbf.append(x);
sbf.append(",");
sbf.append(y);
sbf.append(",");
sbf.append(z);
sbf.append(")");
return sbf.toString();
}
}
public class test01 {
public static void main(String[] args) {
Vector a = new Vector(1,-3,2);
Vector b = new Vector(-1,2,3);
Vector c = new Vector(3,-4,1);
Vector d = new Vector(2,-3,1);
Vector v = new Vector(1,1,0);
Vector u = new Vector(1,1,(float)Math.sqrt(2d));
int k = 5;
System.out.printf( "%s + %s - %s = %s \n",a,b,c,a.add(b).add(c.getInvert()));
System.out.printf( "%d%s = %s \n",k,a,a.times(k));
System.out.printf( "%s の長さは、 %s \n",d,d.len());
System.out.printf( "%s と %s の内積は、%s \n",v,u,Vector.getDot(v,u));
System.out.printf( "%s と %s の外積は、%s \n",v,u,Vector.getCross(v,u));
}
}
【実行結果】
登録:
コメントの投稿 (Atom)
0 件のコメント:
コメントを投稿