/**************************************************************** **** **** This file belongs with the course **** Introduction to Scientific Programming in C++/Fortran2003 **** copyright 2020-2023 Victor Eijkhout eijkhout@tacc.utexas.edu **** **** walk_lib.css : random walks library using std::vector **** ****************************************************************/ #include using std::cin, std::cout; #include using std::ostream; #include using std::for_each; #include #include #include using std::vector; #include ostream &operator<<(ostream &os,const vector &v) { os << "("; for ( auto e : v ) os << e << ","; os << ")"; return os; }; float random_float() { static std::random_device r; static std::default_random_engine static_engine( r() ); std::uniform_real_distribution distribution(-1.f,1.f); return distribution(static_engine); }; float length( const vector& step ) { vector square; int s = step.size(); if (square.size()!=s) square.resize(s); for ( int i=0; i& step,float len=0.f ) { if (len==0.f) len = length(step); if (len==0.f) cout << "Zero vector size " << step.size() << ": " << step << '\n'; assert( len!=0.f ); for_each( step.begin(),step.end(), [len] (float& x) { x /= len; } ); }; bool no_nans( const vector& step ) { bool ok{true}; for_each( step.begin(),step.end(), [&ok] (float x) { ok = ok and not std::isnan(x); } ); return ok; }; //codesnippet walkrandcoord vector random_coordinate( int d ) { auto v = vector(d); for ( auto& e : v ) e = random_float(); return v; }; //codesnippet end //codesnippet walkrandstep vector random_step(int d) { for (;;) { auto step = random_coordinate(d); if ( auto l=length(step); l<=1.f ) { if ( l==0.f ) { /* * Zero lengths can conceivably happen for d==1 * but should not for higher d. */ assert(d==1); } else { normalize(step,l); return step; } } } }; //codesnippet end //codesnippet mosqclass class Mosquito { private: vector pos; public: Mosquito( int d ) : pos( vector(d,0.f) ) { }; //codesnippet end Mosquito( vector pos ) : pos(pos) {}; //codesnippet walkstep void step() { int d = pos.size(); auto incr = random_step(d); for (int id=0; id