ccgsl: a C++ interface for the gnu Scientific Library

Links

Home ·
Download ·
Design ·
Documentation ·
Development ·
Example ·
Bugs ·

Example code

This code illustrates some of the features of ccgsl. This particular code uses C++11 features, though you don’t have to have a compiler capable of compiling new C++11 features to use ccgsl.
#include<iostream>
#include<array>
#include<ccgsl/poly.hpp>
#include<ccgsl/vector.hpp>
#include<ccgsl/math.hpp>
#include<ccgsl/diff.hpp>

// A polynomial and its first derivative
class Polynomial {
public:
  Polynomial( gsl::vector coefficients ) : coefficients( coefficients ){}
  // Evaluate polynomial at x
  double function( double const x ) const {
    return gsl::poly::eval( coefficients, x );
  }
  // Evaluate derivative at x
  double derivative( double const x ) const {
    gsl::poly::eval_derivs( coefficients, x, derivatives );
    return derivatives[1];
  }
  // Get coefficients
  gsl::vector getCoefficients(){
    return coefficients;
  }
private:
  // coefficients, starting wih constant
  gsl::vector coefficients;
  // temporary space to store derivatives
  mutable std::array<double,2> derivatives;
};

int main(){
  // Set up a polynomial 7 + 5x - 12 x^2 + x^3
  Polynomial polynomial( gsl::vector( { 7, 5, -12, 1 } ) );

  // Write coefficients
  size_t index = 0;
  std::cout << "f(x) = ";
  for( auto coefficient : polynomial.getCoefficients() ){
    if( index > 0 ) std::cout << " + ";  
    std::cout << coefficient;
    if( index > 0 ) std::cout << "x";  
    if( index > 1 ) std::cout << "^" << index;  
    ++index;
  }
  std::cout << std::endl;

  // Exact values
  std::cout << "f(2) = " << polynomial.function( 2 ) << "; ";
  std::cout << "f'(2) = " << polynomial.derivative( 2 ) << "; ";
  
  // Central difference quotient
  std::cout << "central difference quotient estimate of f'(2): ";
  // Set up a GSL scalar function
  gsl::function_scl f( polynomial, &Polynomial::function );
  double result, abserr;
  gsl::diff::central( &f, 2, &result, &abserr );
  // print result
  std::cout << result << std::endl;
  
  exit( 0 );
}

Last modified: Thu 29 Mar 2012 03:14 pm

SourceForge.net Logo