Computational Physics - Department of Physics

(Axel Boer) #1

3.3 Classes in C++ 85


// Postmultiplication operator
Vectoroperator(constVector& v,doublescalar){// u = va
returnVector(v)*= scalar;
}


// Premultiplication operator.
Vectoroperator(doublescalar,constVector& v){// u = av
returnv*scalar;// Note the call to postmultiplication operator defined above
}


// Multiplication (product) operator: Matrix times vector
Vectoroperator(constMatrix& A,constVector& v){// u = Av
intm = A.getRows();
intn = A.getColumns();
if(A.getColumns() != v.getLength()){
std::cerr <<"Bad sizes in: Vector operator(const Matrix& A, const Vector& v)";
}
Vector u(m);
for(inti=0; i<m; i++){
for(intj=0; j<n; j++){
u[i] += A[i][j]
v[j];
}
}
returnu;
}


// Division of the entries in a vector by a scalar
Vectoroperator/(constVector& v,doublescalar){
if(!scalar) std::cout <<"Division by zero!"<< std::endl;
return(1.0/scalar)*v;
}


// compute the dot product between two vectors
doubleinner(constVector& u,constVector& v){// dot product
if(u.length != v.length){
std::cout <<"Bad vector sizes in: double inner(const Vector& u, const Vector& v)"<<
std::endl;
}
doublesum = 0.0;
for(inti=0; i<u.length; i++)
sum += u[i]*v[i];
returnsum;
}


doubleVector::inner(constVector& v)const{ // dot product double a = u.inner(v)
if(length != v.length)
std::cout <<"Bad vector sizes in: double Vector::inner(const Vector& v) const"<<
std::endl;
doublesum = 0.0;
for(inti=0; i<v.length; i++)
sum += vec[i]*v.vec[i];
returnsum;
}


// compute the eucledian norm
doubleVector::l2norm()const{
doublenorm = fabs(vec[0]);
for(inti=1; i<length; i++){

Free download pdf