/*************************************************************************
* Name:
* Login:
* Precept:
*
* Description: This class is implemented to be immutable: once the
* client program initializes a Vector, it cannot change any of its
* fields (N or data[i]) either directly or indirectly. Immutability
* is a very desirable feature of a data type.
*
* Output:
* % java-introcs Vector
* x = ( 1.0, 2.0, 3.0, 4.0 )
* y = ( 5.0, 2.0, 4.0, 1.0 )
* x + y = ( 6.0, 4.0, 7.0, 5.0 )
* 10x = ( 10.0, 20.0, 30.0, 40.0 )
* |x| = 5.477225575051661
* <x, y> = 25.0
* |x - y| = 5.0990195135927845
*
* Remarks:
* - See booksite an implementation of a vector of real numbers:
* http://www.cs.princeton.edu/introcs/34nbody/Vector.java
* - Vector is also the name of an unrelated Java library class.
*************************************************************************/
public final class Vector {
private int N; // length of the vector
private double[] data; // array of vector's components
// create the zero vector of length n
public Vector(int N) {
this.N = N;
this.data = new double[N];
}
// create a vector from the array d
public Vector(double[] d) {
// Something is missing here . . .
// We need a defensive copy so client can't alter our copy of data[]
// This isn't it!
double[] data = d;
}
// return a + b
public Vector plus(Vector b) {
Vector a = this;
if (a.N != b.N) {throw new RuntimeException("Dimensions disagree"); }
Vector c = new Vector(N);
for (int i = 0; i < N; 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.N != b.N) {throw new RuntimeException("Dimensions disagree"); }
Vector c = new Vector(N);
for (int i = 0; i < N; 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(N);
for (int i = 0; i < N; i++) {
c.data[i] = factor * data[i];
}
return c;
}
// return the corresponding unit vector
public Vector direction() {
Vector a = this;
return a.times(1.0 / a.magnitude());
}
// return the inner product of this Vector a and b
public double dot(Vector b) {
}
// return the Euclidean norm of this Vector a
public double magnitude() {
Vector a = this;
return Math.sqrt(a.dot(a));
}
// return the corresponding coordinate
public double cartesian(int i) {
return data[i];
}
// return a string representation of the vector
public String toString() {
}
// test client
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("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));
}
}