-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector.java
More file actions
78 lines (68 loc) · 2.08 KB
/
Copy pathVector.java
File metadata and controls
78 lines (68 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
public class Vector {
private int size;
private double[] values;
public Vector(int size){
this.size = size;
}
public void setSize(int newSize){
this.size = newSize;
this.values = null;// clear the values because size has changed
}
public int getSize(){
return this.size;
}
public void setValues(double[] newValues){
// first check new array is the right size
if (newValues.length != this.size){
System.err.println("Wrong size array for the vector");
}
this.values = newValues;
}
public double[] getvalues(){
return this.values;
}
public void print(){// print a vector in a nice format
for (int i = 0; i < this.size; i++){
System.out.print("[");
System.out.print(this.values[i]);
System.out.print(" ");
System.out.println("]");
}
}
public Vector add(Vector x){
if (x.size != this.size){
System.err.println("Vectors differ in size");
}
Vector result = new Vector(this.size);
double[] resultValues = new double[this.size];
result.setSize(this.size);
for (int i = 0; i < this.size; i++){
resultValues[i] = this.values[i] + x.values[i];
}
result.setValues(resultValues);
return result;
}
public Vector multiply(double x){
Vector result = new Vector(this.size);
double[] resultValues = new double[this.size];
result.setSize(this.size);
for (int i = 0; i < this.size; i++){
resultValues[i] = x * this.values[i];
}
result.setValues(resultValues);
return result;
}
public Vector subtract(Vector x){
return this.add(x.multiply(-1));
}
public double dot(Vector x){
if (x.size != this.size){
System.err.println("Vectors differ in size");
}
double total = 0;
for (int i = 0; i < this.size; i++){
total += this.values[i] * x.values[i];
}
return total;
}
}