hi friend,
public final class Vector {
private final int in;
private final double[] data;
public Vector(int in){
this.in = in;
this.data = new double[in];
}
public Vector(double[] d){
in = d.length;
data = new double[in];
for(int i = 0; i < in; i++){
data[i] = d[i];
}
}
public double dot(Vector b){
Vector a = this;
if(a.in != b.in){ throw new RuntimeException("Dimensions don't agree");
}
double sum = 0.0;
for (int i = 0; i < in; i++) {
sum = sum + (a.data[i] * b.data[i]);
}
return sum;
}
public double magnitude(){
Vector a = this;
return Math.sqrt(a.dot(a));
}
public Vector direction(){
Vector a = this;
return a.times(1.0 / a.magnitude());
}
public Vector plus(Vector b){
Vector a = this;
if (a.in != b.in) { throw new RuntimeException("Dimensions don't agree"); }
Vector c = new Vector(in);
for(int i = 0; i < in; i++){
c.data[i] = a.data[i] + b.data[i];
}
return c;
}
// return a - b
public Vector minus(Vector b){
Vector a = this;
if (a.in != b.in) { throw new RuntimeException("Dimensions don't agree"); }
Vector c = new Vector(in);
for(int i = 0; i < in; i++){
c.data[i] = a.data[i] - b.data[i];
}
return c;
}
// create and return a new object whose value is (this * factor)
public Vector times(double factor) {
Vector c = new Vector(in);
for(int i = 0; i < in; i++){
c.data[i] = factor * data[i];
}
return c;
}
// return the corresponding unit vector
public double cartesian(int i){
return data[i];
}
// return a string representation of the vector
public String toString(){
String s = "( ";
for(int i = 0; i < in; i++) {
s = s + data[i] + " ";
}
return s + ")";
}
public static void main(String[] args) {
double[] xdata = { 1.0, 2.0, 3.0, 4.0 };
double[] ydata = { 5.0, 2.0, 4.0, 1.0 };
Vector x = new Vector(xdata);
Vector y = new Vector(ydata);
System.out.println("All result display: ");
System.out.println("x = " + x);
System.out.println("y = " + y);
System.out.println("x + y = " + x.plus(y));
System.out.println("10x = " + x.times(10.0));
System.out.println("|x| = " + x.magnitude());
System.out.println("<x, y> = " + x.dot(y));
System.out.println("|x - y| = " + x.minus(y).magnitude());
}
}
---------------------------------
read for more information,
http://www.roseindia.net/java/