Interior-point-optimisation  1.0-1
Interior-pointoptimisationlibrary
ForwardDifferenceGradientEstimate.cc
Go to the documentation of this file.
1 /*
2  * $Id: ForwardDifferenceGradientEstimate.cc 137 2013-06-29 15:10:31Z jdl3 $
3  * Copyright (C) 2011, 2013 John D Lamb
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or (at
8  * your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18  */
19 
20 #ifdef HAVE_CONFIG_H
21 # include<config.h>
22 #endif
23 
25 
26 using namespace ipo_function::detail;
27 
29  double const h )
30  : function( function ), h { h }{}
31 
32 void
33 ForwardDifferenceGradientEstimate::setVector( gsl::vector const& vector ){
34  // This is where all the work is done. First find functionValue.
35  functionValue = function( vector );
36  // Now find SIZE
37  const size_t SIZE { vector.size() };
38  // Set up storage for f(x + h e_i) and f(x + h e_i + h e_j)
39  auto diffVector = gsl::vector( SIZE );
40  // Fill diffVector
41  for( size_t i { 0 }; i < SIZE; ++i ){
42  double tmp { vector.get( i ) };
43  const_cast<gsl::vector&>( vector ).set( i, tmp + h );
44  diffVector.set( i, function( vector ) );
45  const_cast<gsl::vector&>( vector ).set( i, tmp );
46  // vector returned to original value.
47  }
48 
49  // set up functionGradient
50  if( getSize() != SIZE ) functionGradient = gsl::vector( SIZE );
51  // calculate gradient: forward difference quotient
52  for( size_t i { 0 }; i < SIZE; ++i ){
53  double const diff { diffVector.get( i ) - functionValue };
54  //std::cout << "[" << functionValue << "," << diffVector.get( i ) << "]: "
55  //<< (diff / h) << std::endl;
56  functionGradient.set( i, diff / h );
57  }
58 }
virtual void setVector(gsl::vector const &vector)
Set the vector to a new value.
double functionValue
The function value.
ForwardDifferenceGradientEstimate(Function &function, double const h=std::sqrt(std::numeric_limits< double >::epsilon()))
Find forward difference quotient estimates.
gsl::vector functionGradient
The gradient value.
Namespace for details of ipo_function that are not normally needed to construct and solve a convex op...
size_t getSize() const
Get size of vector for function arguments or zero for arbitrary size.
This class computes a function at a vector.
Definition: Function.hpp:38