Created
May 13, 2020 00:56
-
-
Save eduardonunesp/c54fe20e26775cb8b7531df060b5c7b6 to your computer and use it in GitHub Desktop.
Monte Carlo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <random> | |
#include <vector> | |
#include <math.h> | |
#include <sstream> | |
struct Vector { | |
int x; | |
int y; | |
Vector& operator+=(Vector &o) { | |
x += o.x; | |
y += o.y; | |
return *this; | |
} | |
int distance() { | |
return abs(x) + abs(y); | |
} | |
const std::string print() { | |
std::stringstream ss; | |
ss << "(" << x << "," << y << ")"; | |
return ss.str(); | |
} | |
}; | |
const Vector up { 0, 1 }; | |
const Vector down { 0, -1 }; | |
const Vector left {-1, 0 }; | |
const Vector right { 1, 0 }; | |
Vector& choice() { | |
std::vector<Vector> r_dir { | |
up, down, left, right | |
}; | |
return r_dir.at(rand() % 4); | |
} | |
Vector random_walk(int num_of_walks) { | |
Vector xy{0, 0}; | |
for (int i = 0; i < num_of_walks; i++) { | |
xy += choice(); | |
} | |
return xy; | |
} | |
void test_2() { | |
int number_of_walks = 20000; | |
int walk_length = 30; | |
for (int i = 1; i <= walk_length; i++) { | |
int no_transport = 0; | |
for (int j = 1; j <= number_of_walks; j++) { | |
auto walk = random_walk(walk_length); | |
if (walk.distance() <= 5) { | |
no_transport += 1; | |
} | |
} | |
float no_transport_percentage = (float) no_transport / number_of_walks; | |
std::cout << "Walk size: " << i << " " << " Percent " << 100*no_transport_percentage << std::endl; | |
} | |
} | |
void test_1() { | |
int number_of_walks = 10; | |
int walk_length = 25; | |
for (int i = 1; i <= walk_length; i++) { | |
auto walk = random_walk(number_of_walks); | |
std::cout << walk.print() << " Distance from home: " << walk.distance() << std::endl; | |
} | |
} | |
int main() { | |
srand (time(NULL)); | |
test_1(); | |
test_2(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment