You can learn about hot to generate random number here http://www.cplusplus.com/reference/cstdlib/srand/ then you can compare that random value to a some kind of limit of the circle. For example if your limit is 50 any number that more than 50 is land outside the cirle. And you'll need to repeat it until "hotdog value" times
I hope I'm on right track. Don't really understand montecarlo metod
A way of generating floating point number in range [low, high] using C random functions from cstdlib (I assume that for Monte-Carlo method you would need doubles):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
#include <iostream>
#include <cstdlib>
#include <ctime>
double random(double low, double high)
{
double range = high - low;
return low + (static_cast<double>(std::rand()) / RAND_MAX) * range;
}
int main ()
{
std::srand(std::time(nullptr));
for(int i = 0; i < 10; ++i)
std::cout << random(0, 5) << '\n';
}
However rand() will not give you very good random numbers. Better way to do this would be using C++11 <random> header:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
#include <iostream>
#include <random>
#include <ctime>
double random(double low, double high)
{
//It would be better to use random_device for enthropy generation
//But for now we will use this
static std::mt19937 rng(std::time(nullptr));
std::uniform_real_distribution<> dis(low, high);
return dis(rng);
}
int main ()
{
for(int i = 0; i < 10; ++i)
std::cout << random(0, 5) << '\n';
}
So to implement Monte-Carlo method you woukd need:
(I assume that the square you use have side length of 1)
Generate 2 random numbers from 0 to 1. (this will be coords of the point)
Pass them to PointInCircle() function
Check their distance to the 0.0 point (Using Pythagoras theorem)
If that distance is not larger than circle radius (equals to the square side), return true (point is in circle) else return false.
Then you need to divide amount of points in circle by total amount of points generated and multiply by four. Resulting value will be close to Pi
1) Check implementation of random() again. You missed low + part.
2) Passing is simple:
1 2 3 4 5 6
int x = random(0, 1000);
int y = random(0, 1000);
/*something using return value*/ PointInCircle(x, y);
//or directly:
/*something using return value*/ PointInCircle(random(0, 1000), random(0, 1000));
Why do you have two randomX and randomY functions? They are comletely identical. So you will not need two of them.
Is the code up there how it's supposed to be done?
First of all line 30 does not do what you thinl it is doing. It is actually creating boolean variable called PointInCircle with a value of false(with very small chance of true)
YOu do not need to output your values.
You need to generate Hotdog amount of points, pass each of them in PointInCircle function and count, how many points are in circle.
After that you need to apply formula to calculate value of Pi