📄 brownian.cpp
字号:
#include <iostream>#include <cmath> // for sin, cos, sqrt#include "randgen.h"#include "prompt.h"#include "mathutils.h" // for PI#include "point.h"using namespace std;// simluate two-dimensional random walk// Owen Astrachan, 6/20/95, modified 6/29/96, modified 5/1/99class RandomWalk2D{ public: RandomWalk2D(long maxSteps, int size); // # of steps, size of one step void Init(); // take first step of walk bool HasMore(); // returns false if walk finished, else true void Next(); // take next step of random walk void Simulate(); // complete an entire random walk long TotalSteps() const; // total # of steps taken by molecule Point Position() const; // current position Point Current() const; // alias for Position private: void TakeStep(); // simulate one step of walk Point myPosition; // coordinate of current position long mySteps; // # of steps taken int myStepSize; // size of step long myMaxSteps; // maximum # of steps allowed};RandomWalk2D::RandomWalk2D(long maxSteps,int size) : myPosition(), mySteps(0), myStepSize(size), myMaxSteps(maxSteps)// postcondition: walker initialized{}void RandomWalk2D::TakeStep()// postcondition: one step of random walk taken{ RandGen gen; // random number generator double randDirection = gen.RandReal(0,2*PI); myPosition.x += myStepSize * cos(randDirection); myPosition.y += myStepSize * sin(randDirection); mySteps++;}void RandomWalk2D::Init()// postcondition: Init step of random walk taken{ mySteps = 0; myPosition = Point(0,0); TakeStep();}bool RandomWalk2D::HasMore()// postcondition: returns false when random walk is finished// i.e., when # of steps taken >= max. # of steps // return true if walk still in progress{ return mySteps < myMaxSteps;}void RandomWalk2D::Next()// postcondition: next step in random walk simulated { TakeStep();}void RandomWalk2D::Simulate(){ for(Init(); HasMore(); Next()) { // simulation complete using iterator methods }}long RandomWalk2D::TotalSteps() const// postcondition: returns number of steps taken by molecule{ return mySteps;}Point RandomWalk2D::Position() const// postcondition: return molecule's position{ return myPosition;}Point RandomWalk2D::Current() const// postcondition: return molecule's position{ return myPosition;}int main(){ long numSteps= PromptRange("enter # of random steps",1L,1000000L); int stepSize= PromptRange("size of one step",1,20); int trials= PromptRange("number of simulated walks",1,1000); RandomWalk2D molecule(numSteps,stepSize); int k; double total = 0.0; Point p; for(k=0; k < trials; k++) { molecule.Simulate(); p = molecule.Position(); total += p.distanceFrom(Point(0,0)); // total final distance from origin } cout << "average distance from origin = " << total/trials << endl; return 0;}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -