Skip to content

Instantly share code, notes, and snippets.

@mgronhol
Last active August 29, 2015 13:57
Show Gist options
  • Save mgronhol/9447936 to your computer and use it in GitHub Desktop.
Save mgronhol/9447936 to your computer and use it in GitHub Desktop.
Simple vector class in java
public class Vektori {
public double x, y, z;
public static Vektori fromPolar( double r, double phi ){
return new Vektori( r * Math.cos( phi ), r * Math.sin( phi ), 0 );
}
public Vektori(){
this.x = 0;
this.y = 0;
this.z = 0;
}
public Vektori( double x, double y ){
this.x = x;
this.y = y;
this.z = 0;
}
public Vektori( double x, double y, double z ){
this.x = x;
this.y = y;
this.z = z;
}
Vektori add( Vektori b ){
return new Vektori( this.x + b.x, this.y + b.y, this.z + b.z );
}
Vektori sub( Vektori b ){
return new Vektori( this.x - b.x, this.y - b.y, this.z - b.z );
}
Vektori scale( double k ){
return new Vektori( this.x * k, this.y * k, this.z * k );
}
double dot( Vektori b ){
return this.x * b.x + this.y * b.y + this.z * b.z;
}
double length(){
return Math.sqrt( this.x*this.x + this.y*this.y + this.z*this.z );
}
Vektori unit(){
double l = 1.0/this.length();
return this.scale( l );
}
Vektori cross( Vektori b ){
/*
|i j k |
|ax ay az|
|bx by bz|
*
(ay*bz - az*by)i + (az*bx - ax*bz )j + (ax*by + ay*bx)k
*
*/
return new Vektori(
this.y*b.z - this.z*b.y,
this.z*b.x - this.x*b.z,
this.x*b.y - this.y*b.x
);
}
/*public static void main( String[] args ){}*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment