my_vector.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * Copyright 2011-2012 Mario Mulansky
  3. * Copyright 2012-2013 Karsten Ahnert
  4. *
  5. * Distributed under the Boost Software License, Version 1.0.
  6. * (See accompanying file LICENSE_1_0.txt or
  7. * copy at http://www.boost.org/LICENSE_1_0.txt)
  8. *
  9. * Example for self defined vector type.
  10. */
  11. #include <vector>
  12. #include <boost/numeric/odeint.hpp>
  13. //[my_vector
  14. template< size_t MAX_N >
  15. class my_vector
  16. {
  17. typedef std::vector< double > vector;
  18. public:
  19. typedef vector::iterator iterator;
  20. typedef vector::const_iterator const_iterator;
  21. public:
  22. my_vector( const size_t N )
  23. : m_v( N )
  24. {
  25. m_v.reserve( MAX_N );
  26. }
  27. my_vector()
  28. : m_v()
  29. {
  30. m_v.reserve( MAX_N );
  31. }
  32. // ... [ implement container interface ]
  33. //]
  34. const double & operator[]( const size_t n ) const
  35. { return m_v[n]; }
  36. double & operator[]( const size_t n )
  37. { return m_v[n]; }
  38. iterator begin()
  39. { return m_v.begin(); }
  40. const_iterator begin() const
  41. { return m_v.begin(); }
  42. iterator end()
  43. { return m_v.end(); }
  44. const_iterator end() const
  45. { return m_v.end(); }
  46. size_t size() const
  47. { return m_v.size(); }
  48. void resize( const size_t n )
  49. { m_v.resize( n ); }
  50. private:
  51. std::vector< double > m_v;
  52. };
  53. //[my_vector_resizeable
  54. // define my_vector as resizeable
  55. namespace boost { namespace numeric { namespace odeint {
  56. template<size_t N>
  57. struct is_resizeable< my_vector<N> >
  58. {
  59. typedef boost::true_type type;
  60. static const bool value = type::value;
  61. };
  62. } } }
  63. //]
  64. typedef my_vector<3> state_type;
  65. void lorenz( const state_type &x , state_type &dxdt , const double t )
  66. {
  67. const double sigma( 10.0 );
  68. const double R( 28.0 );
  69. const double b( 8.0 / 3.0 );
  70. dxdt[0] = sigma * ( x[1] - x[0] );
  71. dxdt[1] = R * x[0] - x[1] - x[0] * x[2];
  72. dxdt[2] = -b * x[2] + x[0] * x[1];
  73. }
  74. using namespace boost::numeric::odeint;
  75. int main()
  76. {
  77. state_type x(3);
  78. x[0] = 5.0 ; x[1] = 10.0 ; x[2] = 10.0;
  79. // make sure resizing is ON
  80. BOOST_STATIC_ASSERT( is_resizeable<state_type>::value == true );
  81. // my_vector works with range_algebra as it implements
  82. // the required parts of a container interface
  83. // no further work is required
  84. integrate_const( runge_kutta4< state_type >() , lorenz , x , 0.0 , 10.0 , 0.1 );
  85. }