-
Notifications
You must be signed in to change notification settings - Fork 4
/
Vector.cpp
126 lines (105 loc) · 1.92 KB
/
Vector.cpp
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#include "stdafx.h"
#include "Vector.h"
Vector operator+(const Vector& lhs, const Vector& rhs)
{
return Vector(lhs) += rhs;
}
Vector operator-(const Vector& lhs, const Vector& rhs)
{
return Vector(lhs) -= rhs;
}
Vector operator*(const Vector& lhs, const double& rhs)
{
return Vector(lhs) *= rhs;
}
Vector operator*(const double& lhs, const Vector& rhs)
{
return Vector(rhs) *= lhs;
}
Vector operator/(const Vector& lhs, const double& rhs)
{
return Vector(lhs) /= rhs;
}
Vector operator-(const Vector& lhs)
{
return Vector(lhs) *= -1;
}
double InnerProduct(const Vector& lhs, const Vector& rhs)
{
if (lhs.Length() != rhs.Length()) throw WrongDimensionException();
double accum(0);
int len = lhs.Length();
for (int i = 0; i<len; i++)
{
accum += lhs[i] * rhs[i];
}
return accum;
}
Vector& Vector::operator+=(const Vector& rhs)
{
if (Cols != rhs.Cols) throw WrongDimensionException();
for (int i = 0; i<Cols; i++)
{
rep[i] += rhs[i];
}
return *this;
}
double Vector::Normalize()
{
double mag = Magnitude();
if (mag <= 0) return 0;
// assert(mag > 0);
*this /= mag;
return mag;
}
double Vector::Magnitude() const
{
double mag = sqrt(Magnitude2());
return mag;
}
double Vector::Magnitude2() const
{
double mag2 = 0;
for (int i = 0; i<Cols; i++)
mag2 += rep[i] * rep[i];
return mag2;
}
Vector& Vector::operator-=(const Vector& rhs)
{
if (Cols != rhs.Cols) throw WrongDimensionException();
for (int i = 0; i<Cols; i++)
{
rep[i] -= rhs[i];
}
return *this;
}
Vector& Vector::operator*=(const double& rhs)
{
for (int i = 0; i<Cols; i++)
{
rep[i] *= rhs;
}
return *this;
}
Vector& Vector::operator/=(const double& rhs)
{
for (int i = 0; i<Cols; i++)
{
rep[i] /= rhs;
}
return *this;
}
int Vector::Length() const
{
return Cols;
}
void Vector::Resize(int size)
{
rep.resize(size, 0);
fill(rep.begin(), rep.end(), 0);
Cols = size;
}
void Vector::clear()
{
std::fill(rep.begin(), rep.end(), 0);
}