-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVector.java
More file actions
88 lines (77 loc) · 2.12 KB
/
Vector.java
File metadata and controls
88 lines (77 loc) · 2.12 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
79
80
81
82
83
84
85
86
87
88
/**
* Vector.java, ECE4960-P2
* Created by Yuan He(yh772) on 2018-03-04
* Platform: Java 8, Eclipse, MacOS
* Copyright © 2018 Yuan He. All rights reserved.
*
* Project3, type Vector:
* Constructs type Vector, and implement Vector operations.
*/
public class Vector {
/* Class variants: Data structures for keeping the Vector */
double[] v;
int len;
/* Class methods:*/
/**Function: Constructor, construct a Vector with an array
* @param: double[] a
* @return : None*/
public Vector(double[] a) {
v = a.clone();
len = v.length;
}
/**Function: Constructor2, construct an empty Vector by only indicating its length
* @param: int length
* @return: None*/
public Vector(int len) {
v = new double[len];
this.len = len;
}
/**Function: Compare two Vectors element to element to see if they are equivalent to each other
* @param: this.Vector, Vector B
* @return: int indicator, with 0 representing in-equivalent and 1 representing equivalent*/
public int equals(Vector B) {
for(int i=0; i<len; i++) {
if(v[i] != B.v[i])
return 0;
}
return 1;
}
/**Function: vectorA + d*VectorB
* @param: Vector B, double d
* @return: Vector sum*/
public Vector add(Vector B, double d) {
// Keep function invariants true
assert B.len == len: "Unmatched matrix sizes!";
// Iteratively add two vectors' corresponding values into the sum
Vector sum = new Vector(len);
for(int i=0; i<len; i++) {sum.v[i] = v[i] + d*B.v[i];}
return sum;
}
/**Function: this.Vector * t
* @param: double t (the scaler)
* @return: new Vector res*/
public Vector scale(double t) {
double res[] = new double[len];
for(int i=0; i<len; i++) {
res[i] = (double)v[i]*(double)t;
}
return new Vector(res);
}
/**Function: Calculate the norm of this.Vector
* @param: None
* @return: double*/
public double norm() {
double sum = 0;
for(int i=0; i<len; i++) {
sum += v[i] * v[i];
}
return Math.pow(sum, 0.5);
}
/**Function: Keep function invariants true: 0 <= index < size
* @param: int i, int j
* @return: None*/
public void assertInd(int i, int j) {
assert i>=0 && i<len;
assert j>=0 && j<len;
}
}