qrand is returning always 0 - c++

I need to get random numbers between 0 and 1.
As 0.54321, 0.8912, 0.1234342, 0.0000123 and etc
I put this code in my main and also Application constructor:
qsrand(QDateTime::currentDateTime().toTime_t());
And used this code inside one of my slots:
float prob = qrand() % 1;
I tried int, double as a return value, but it is always returning 0.
Any ideas what is going on?
Thanks

qrand() generates integer numbers between 0 to RAND_MAX and every number is perfectly divisible by 1 and giving remainder as 0. Try this instead:
float prob = (float) qrand() / (RAND_MAX+1); // 1 is exclusive

Related

not getting random values even with srand(time(NULL))

Even after including srand(time(NULL)) at the start of my function, (function is only called once in main) I get the same random value for r1 every time I run the program. r2 and r3 get random values fine, but I need random decimal values between 0.1 and 10.0 so what's wrong with the line containing r1?
void randNums(float &r1, float &r2, float &r3) {
srand(time(NULL));
r1 = (10 * (rand())/ (float)RAND_MAX);
r2 = 1 + (rand() % 10);
r3 = 1 + (rand() % 10);
}
I just removed the srand line and used the function to print it out a couple of times and it generated random numbers. When I was using your code to generate random numbers, it apparently displayed the same 3 random number values for r1, r2, and r3 no matter how many times I ran it. I think what Mooing Duck said was true. It might be because of overflow from 10 * rand() code.
The only downside to this is, if you were to rerun your code it will generate the same random numbers as the last session.

How do I go about getting the real result for 50%60 in C++

I please check this problem I'm creating a Time Base app but I'm having problem getting to work around the modulus oper (%) I want the remainder of 50%60 which I'm expecting to output 10 but it just give me the Lhvalues instead i.e 50. How do I go about it.
Here is a part review of the code.
void setM(int m){
if ((m+min)>59){
hour+=((min+m)/60);
min=0;
min=(min+m)%60;
}
else min+=m;
}
In the code m is passed in as 50 and min is passed in as 10
How do I get the output to be 10 for min in this equation min=(min+m)%60; without reversing the equation i.e
60%(min+m)
in C++ expression a % b returns remainder of division of a by b (if they are positive. For negative numbers sign of result is implementation defined).
you should do : 60 % 50 if you want to divide by 50
Or, if you want to get mins, i think you don't need to make min=0.
When you do 50 % 60, you get a remiainder of 50 since 50 cannot be divided by 60.
To get around this error, you can try doing do something like 70 % 60 to get the correct value as a result, since you do not want to use 60 % 50
This would follow the following logic:
Find the difference between 60 and min + m after min is set to zero if min + mis less than 60. Store it in a variable var initially set to zero.
check if the result is negative; if it is, then set it to positive by multiplying it by -1
When you do the operation, do min = ((min + m) + var) % 60; instead.
***Note: As I am unfamiliar with a Time Base App and what its purpose is, this solution may or may not be required, hence please inform me in the comments before downvoting if I there is anything wrong with my answer. Thanks!
It looks like you are trying to convert an integral number of minutes to an hour/minute pair. That would look more like this instead:
void setM(int m)
{
hour = m / 60;
min = m % 60;
}
If you are trying to add an integral number of minutes to an existing hour/minute pair, it would look more like this:
void addM(int m)
{
int value = (hour * 60) + min;
value += m;
hour = value / 60;
min = value % 60;
}
Or
void addM(int m)
{
setM(((hour * 60) + min) + m);
}

About random numbers in C++

I am really new to C++. I am following a free online course, and one thing I had to do was to create a program which could scramble the characters of a string.
So, I created a function who received the word as parameter and returned the scrambled word. ctime and cstdlib were included and srand(time(0)); declared in the main.
Basically, the function looked like this :
std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);
for (int i = baseWord.length; i >= 0; i--)
{
if (i != 0)
{
pos = rand() % i;
mixWord += baseWord[pos];
baseWord.erase(pos,1);
}
else
{
mixWord += baseWord[0];
}
}
return mixWord;
}
And it worked just fine. But the correct solution was
std::string mixingWord(std::string baseWord)
{
std::string mixWord;
int pos(0);
while (baseWord.size() != 0)
{
pos = rand() % baseWord.size();
mixWord += baseWord[pos];
baseWord.erase(pos, 1);
}
return mixWord;
}
And it works fine as well.
My question is :
Why is the solution working ?
From what I understood, this :
rand() % value
gives out a value between 0 and the value given.
SO, since baseWord.size() returns, let's say 5 in the event of a word like HELLO. rand will generate a number between 0 and 5. So it COULD be 5. and baseWord[5] is out of bound, so it should crash once in a while, but I tried it over 9000 times (sorry, dbz reference), and it never crashed.
Am I just unlucky, or am I not understanding something ?
x % y gives the remainder of x / y. The result can never be y, because if it was, then that would mean y could go into x one more time, and the remainder would actually be zero, because y divides x evenly. So to answer your question:
Am I just unlucky, or am I not understanding something ?
You're misunderstanding something. rand() % value gives a result in the range [0,value - 1] (assuming value is positive), not [0, value].
rand() % 100 returns number between 0 and 99. This is 100 NUMBERs but includes 0 and does not include 100.
A good way to think about this is a random number (1000) % 100 = 0. If I mod a random number with the number N then there is no way to get the number N back.
Along those lines
pos = rand() % baseWord.size();
will never return pos = baseWord.size() so in your case there will not be an indexing issue
I guess you just misunderstood the modulo operator. a % b, with a and b any integer, will return values between 0 and b-1 (inclusive).
As for your HELLO example, it will only return values between 0 and 4, therefore will never encounter out of bound error.

Having trouble understanding a portion of code (bit operation)

I can't understand how to count number of 1's in binary representation.
I have my code, and I hope someone can explain it for me.
Code:
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
Why while ? For example if i have 1011, it wouldn't stop at 0?
Why nr += x%2 ?
Why x/=2 ?!
First:
nr += x % 2;
Imagine x in binary:
...1001101
The Modulo operator returns the remainder from a / b.
Now the last bit of x is either a 0, in which case 2 will always go into x with 0 remainder, or a 1, in which case it returns a 1.
As you can see x % 2 will return (if the last bit is a one) a one, thus incrementing nr by one, or not, in which case nr is unchanged.
x /= 2;
This divides x by two, and because it is a integer, drops the remainder. What this means is is the binary was
....10
It will find out how many times 2 would go into it, in this case 1. It effectively drops the last digit of the binary number because in base 2 (binary) the number of times 2 goes into a number is just the same as 'shifting' everything down a space (This is a poor explanation, please ask if you need elaboration). This effectively 'iterates' through the binary number, allowing the line about to check the next bit.
This will iterate until the binary is just 1 and then half that, drop the remainder and x will equal 0,
while (x != 0)
in which case exit the loop, you have checked every bit.
Also:
'count`is possibly not the most descriptive name for a function, consider naming it something more descriptive of its purpose.
nr will always be a integer greater or equal to zero, so you should probably have the return type unsigned int
int count (int x)
{
int nr=0;
while(x != 0)
{
nr+=x%2;
x/=2;
}
return nr;
}
This program basically gives the numbers of set bits in a given integer.
For instance, lets start with the example integer 11 ( binary representation - 1011).
First flow will enter the while loop and check for the number, if it is equal to zero.
while(11 != 0)
Since 11 is not equal to zero it enter the while loop and nr is assigned the value 1 (11%2 = 1).nr += 11%2;
Then it executes the second line inside the loop (x = x/2). This line of code assigns the value 5 (11/2 = 5 ) to x.
Once done with the body of the while loop, it then again checks if x ie 5 is equal to zero.
while( 5 != 0).
Since it is not the case,the flow goes inside the while loop for the second time and nr is assigned the value 2 ( 1+ 5%2).
After that the value of x is divided by 2 (x/2, 5/2 = 2 )and it assigns 2 to x.
Similarly in the next loop, while (2 != 0 ), nr adds (2 + 2%2), since 2%2 is 0, value of nr remains 2 and value of x is decreased to 1 (2/2) in the next line.
1 is not eqaul to 0 so it enters the while loop for the third time.
In the third execution of the while loop nr value is increased to 3 (2 + 1%2).
After that value of x is reduced to 0 ( x = 1/2 which is 0).
Since it fails the check (while x != 0), the flow comes out of the loop.
At the end the value of nr (Which is the number of bits set in a given integer) is returned to the calling function.
Best way to understand the flow of a program is executing the program through a debugger. I strongly suggest you to execute the program once through a debugger.It will help you to understand the flow completely.

weighted boolean value - scaling

I am not sure how to implement this, but here is the description:
Take a number as input in between the range 0-10 (0 always returning false, 10 always returning true)
Take the argument which was received as input, and pass into a function, determining at runtime whether the boolean value required will be true or false
Say for example:
Input number 7 -> (7 has a 70% chance of generating a true boolean value) -> pass into function, get the boolean value generated from the function.
This function will be run multiple times - perhaps over 1000 times.
Thanks for the help, I appreciate it.
bool func(int v) {
float f = rand()*1.0f/RAND_MAX;
float vv= v / 10.0f;
return f < vv;
}
I would say generate a random number representing a percentage (say 1 to 100) then if the random number is less then or equal to the percentage chance mark it as true, else mark it as false.
This is an interesting question! Here's what I think you should do, in pseudo code:
boolean[] booleans = new boolean[10]; //boolean array of length 10
function generateBooleans(){
loop from i = 0 to 10:
int r = random(10); //random number between 0 and 9, inclusive
if(r < i){
booleans[i] = true;
}
}
}
You can then compare the user's input to your boolean array to get the pre-determined boolean value:
boolean isTrue = booleans[userInputNumber]
Here's an idea , I'm not sure that's it's gonna be helpful;
bool randomChoice(int number){
int result =rand() % 10;
return number>=result;
}
Hope it's helpful