I am very new to c++. And, I need to create random cordinates. I need to have my coordinate must lie with in -1<x<1 and -1<y<1. Can anyone please help me in solving the issue? I am very beginner in c++. Help be greatly appreciated!
Look at the support C++ has in the C++ library <random>, a good start would be looking at the Mersenne Twister 19937 generator (class) and the Uniform real distribution (class template).
http://www.cplusplus.com/reference/random/mt19937/
http://www.cplusplus.com/reference/random/uniform_real_distribution/
There are examples at the links how to use.
There will be people who scream that using the C library rand() function is easier, but there are serious problems with using it. It is outdated, sloppy and inefficient.
Writing new C++ using rand() is like trying to create a mnemonic memory circuit using stone knives and bear skins.
http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/
You can use the rand function and define your precision.
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <time.h>
int main()
{
srand(time(NULL)); //This makes your "rand" function generate a different number every time the program is run
float x;
x= 0.01 * rand()%100; // This gives to numbers after the decimal
if( (rand()%2 == 1) //This is..
x*= -1; //..for a 1/2 chance of ending up being negative
return 0;
}
And better yet, to make sure std::cout prints a decimal with full precision and not printing redundant zero digits after a double (in some cases), use this :
And in your code (function main()), you do the following :
1 2 3 4 5 6 7 8 9
cout.setf(ios::fixed); // You do it only once
double x = random_d();
cout.precision(precision_d(x)); // Always do this before printing!
cout << x << endl;
double y = random_d();
cout.precision(precision_d(y)); // Always do this before printing!
cout << y << endl;
Had you tested my function very carefully, you would really not have said that.
I am not saying it doesn't work, I am saying it is overkill, With C++ library <random> one can create a random number in a few LOC. Look at the example here, the same one FurryGuy linked:
Failing that, it's easy to use rand to create a sufficiently large number, then divide that by a power of 10 to achieve a double in the required range in a few LOC.
You've bloated the size of the code, and used a very inefficient random engine. Even the C standard recommends NOT using rand(). See the C11 standard, note 295.
I'll continue using better tools designed for C++, not ancient C.
Something the C library random functions do not produce, never have and never will.
http://statistics.about.com/od/ProbHelpandTutorials/a/What-Is-A-Uniform-Distribution.htm
http://stattrek.com/statistics/dictionary.aspx?definition=uniform_distribution
closed account wrote:
I can't afford to lose this time which is why I participate