Create a vector class incorporating the following features: a. a constructor tak
ID: 3545931 • Letter: C
Question
Create a vector class incorporating the following features:
a. a constructor taking an array of doubles as an argument
b. a toString method returning proper vector notation , e.g<1.0, -1.0, 0.0, 2.0>
c. a method to return the size (number of componenets) of a vector
d. a method to return the norm of the vector
e. a method unitize that will return a unit vector for a given vector
f. a method scale for computing the product of a scalar and a vector
g. a method add for adding two vectors
h. a method dot for computing the dot product of two vectors
i. a method cross for computing the cross product of two vectors
Explanation / Answer
The answer does not contains the last one(cross product), because I cannot find the definition of n-dim cross product
public class Vector
{
private double[] array;
public Vector(double[] v)
{
array = new double[v.length];
for (int i = 0; i < v.length; i++)
array[i] = v[i];
}
public int size()
{
return array.length;
}
public String toString()
{
String s = "<";
for (int i = 0; i < array.length; i++)
{
if (i > 0)
s += ", ";
s += array[i];
}
return s + ">";
}
public double norm()
{
double sum = 0;
for (int i = 0; i < array.length; i++)
sum += array[i] * array[i];
return Math.sqrt(sum);
}
public Vector unitize()
{
double[] result = new double[array.length];
double n = norm();
for (int i = 0; i < array.length; i++)
result[i] = array[i] / n;
return new Vector(result);
}
public Vector scale(double scalar)
{
double[] result = new double[array.length];
for (int i = 0; i < array.length; i++)
result[i] = array[i] * scalar;
return new Vector(result);
}
public Vector add(Vector another)
{
if (array.length != another.array.length)
return null;
double[] result = new double[array.length];
for (int i = 0; i < array.length; i++)
result[i] = array[i] + another.array[i];
return new Vector(result);
}
public double dot(Vector another)
{
if (array.length != another.array.length)
return 0;
double result = 0;
for (int i = 0; i < array.length; i++)
result += array[i] * another.array[i];
return result;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.