473,729 Members | 2,150 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

generate 2 random numbers in rapid sequence

I need to generate 2 random numbers in rapid sequence from either PHP or
mysql.
I have not been able to do either. I get the same number back several times
from PHP's mt_rand() and from mysql's RAND().
any ideas?

I suppose I could use the current rancom number as the seed for the next
random number. but would that really work?
Apr 23 '06 #1
12 5227
People who work with computers often talk about their system's "random
number generator" and the "random numbers" it produces. However numbers
calculated by a computer through a deterministic process, cannot, by
definition, be random. Given knowledge of the algorithm used to create the
numbers and its internal state, you can predict all the numbers returned by
subsequent calls to the algorithm, whereas with genuinely random numbers,
knowledge of one number or an arbitrarily long sequence of numbers is of no
use whatsoever in predicting the next number to be generated.

Computer-generated "random" numbers are more properly referred to as
pseudo-random numbers, and pseudo-random sequences of such numbers. A
variety of clever algorithms have been developed which generate sequences of
numbers which pass every statistical test used to distinguish random
sequences from those containing some pattern or internal order.

PHP has a number of inbuilt random functions such as rand(). This function
must be first seeded by srand() in order for it to work properly.

<?php

// Range of numbers

// Minimum number
$min = "1";

// Maximum number
$max = "10";

srand((double) microtime() * 1000003);
// 1000003 is a prime number

echo "rand() pseudo-random number".
rand($min, $max);

?>
Apr 23 '06 #2
A less computationally expensive method of accomplishing the same thing is
to use the mt_rand() function. This function uses the Mersenne Twister
algorithm and is considerably faster than rand(). In addition as of PHP
version 4.2.0 there is no need to seed the mt_rand() random number generator
with srand() or mt_srand()

<?php

// Range of numbers

// Minimum number
$min = "1";

// Maximum number
$max = "10";

echo "mt_rand() Mersenne Twister pseudo-random number: ".
mt_rand($min, $max);

?>
Apr 23 '06 #3

"Domestos" <an******@virgi n.netspam> wrote in message
news:1D******** ***********@new sfe2-win.ntli.net...
A less computationally expensive method of accomplishing the same thing is
to use the mt_rand() function. This function uses the Mersenne Twister
algorithm and is considerably faster than rand(). In addition as of PHP
version 4.2.0 there is no need to seed the mt_rand() random number
generator with srand() or mt_srand()

<?php

// Range of numbers

// Minimum number
$min = "1";

// Maximum number
$max = "10";

echo "mt_rand() Mersenne Twister pseudo-random number: ".
mt_rand($min, $max);

?>


I know about these. that's why I mentioned them. my problem, as I stated,
is that when I use them in an inline image generator to randomly select an
image from a database, I get the same images on the page. I refresh, I get a
different image because microtime has changed, but both images are again the
same.

This is supposed to be a random image picker. I don't even care if it's
pseudo-random, as long as I get something that looks like a different image
every time.

any ideas?
Apr 23 '06 #4

"Domestos" <an******@virgi n.netspam> wrote in message
news:1D******** ***********@new sfe2-win.ntli.net...
A less computationally expensive method of accomplishing the same thing is
to use the mt_rand() function. This function uses the Mersenne Twister
algorithm and is considerably faster than rand(). In addition as of PHP
version 4.2.0 there is no need to seed the mt_rand() random number
generator with srand() or mt_srand()

<?php

// Range of numbers

// Minimum number
$min = "1";

// Maximum number
$max = "10";

echo "mt_rand() Mersenne Twister pseudo-random number: ".
mt_rand($min, $max);

?>


and by the way, I've tried PHP manual's suggested code
<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_s eed());
$randval = mt_rand();
?>

but it doesn't make any difference. same result.

I've also tried
$q1=mysql_query ("SELECT MAX(pid) AS a FROM cpg133_pictures ", $link2);
if ($row=mysql_fet ch_assoc($q1)) {
time_nanosleep( 0, 100000);
mt_srand(make_s eed()+$row['a']+rand());
$n=mt_rand(1,$r ow['a']);
but the 100ms nanosleep (which should affect microtime) didn't do anything
either, neither does the mt_srand. maybe the nanosleep never did anything
because it was too small for execution on UNIX.

I have also tried feeding $n into mt_srand(). between calls, makes no
difference. apparently mt_srand is set by default in PHP by microtime().
so when the interpreter starts up for the 2nd session of my image generator,
I'm stuck.

I had thought I could at least get something decent out of mysql's RAND().
Apr 23 '06 #5
>I need to generate 2 random numbers in rapid sequence from either PHP or
mysql.
Same page hit or different page hits? I cannot explain why you
would get the same number in rapid sequence from several calls on
the same hit.
I have not been able to do either. I get the same number back several times
from PHP's mt_rand() and from mysql's RAND().
any ideas?
When PHP starts up, the seed gets initialized to <SOMETHING>,
possibly based on microtime(), but I really don't care. Apache/PHP
don't get restarted very often. With a good host, it could easily
be less than once a month. However, once PHP starts, it's fixed.

It is likely that if Apache fork()s for a given hit, the seed stays
initialized to <SOMETHING> unless you explicitly set it. Any changes
to that by more calls to get pseudo-random numbers are discarded
when that instance of Apache exits. To get different values, you
need to explicitly set the seed to a function of something other
than just microtime().

Things to use for a seed (jumble them all together, as in concatenate,
then take md5 of result, then convert some of md5 result to integer):
microtime()
getmypid()
$_SERVER['UNIQUE_ID'] (Apache only, and may need a module turned on)
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PORT']

Actually, using just the first two should be sufficient, as the
pair (microtime(), getmypid()) should be unique. However, to get
more entropy, throw in some of the others.

If you are using pseudo-random numbers to select one of 100 images,
expect the same image twice in a row about 1% of the time, unless
you have code to deal with this. My suggestion is to not attempt
to avoid this.
I suppose I could use the current rancom number as the seed for the next
random number. but would that really work?


It's a very BAD idea to seed a pseudo-random number generator
multiple times in the same run. Using the output of the random
number generator as a new seed is also not a good idea. It's very
easy to cripple a good pseudo-random number generator with a poor
method of choosing a seed. The problem you're having with microtime()
demonstrates this. Seed once. Use a good source of (pseudo-)randomness.
microtime() alone doesn't qualify if you require rapid-fire results.

Gordon L. Burditt
Apr 23 '06 #6

"Gordon Burditt" <go***********@ burditt.org> wrote in message
news:12******** *****@corp.supe rnews.com...
I need to generate 2 random numbers in rapid sequence from either PHP or
mysql.
Same page hit or different page hits? I cannot explain why you
would get the same number in rapid sequence from several calls on
the same hit.

same page hit on the webserver to a .html file, which has 2 <img
src=img.php> elements.
on a multiprocessor webserver, this may be occurring simultaneously.

I have not been able to do either. I get the same number back several
times
from PHP's mt_rand() and from mysql's RAND().
any ideas?
When PHP starts up, the seed gets initialized to <SOMETHING>,
possibly based on microtime(), but I really don't care. Apache/PHP
don't get restarted very often. With a good host, it could easily
be less than once a month. However, once PHP starts, it's fixed.

It is likely that if Apache fork()s for a given hit, the seed stays
initialized to <SOMETHING> unless you explicitly set it. Any changes
to that by more calls to get pseudo-random numbers are discarded
when that instance of Apache exits. To get different values, you
need to explicitly set the seed to a function of something other
than just microtime().


which makes sense. if all set to microtime, you would still get the same
images.

Things to use for a seed (jumble them all together, as in concatenate,
then take md5 of result, then convert some of md5 result to integer):
microtime()
getmypid()
believe it or not, on these 2 I get the same pictures. frustrating.
$_SERVER['UNIQUE_ID'] (Apache only, and may need a module turned on)
Don't think I have that option. sure sounds good though.
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PORT']
these two won't make it unique, because both images are going to be all on
the same page.
mt_srand(make_s eed()+getmypid( )+$_SERVER['UNIQUE_ID']);
$n=mt_rand(1,$r ow['a']);
tried this, but still doesn't do it. I don't even get an error on
$_SERVER['UNIQUE_ID']. I think it's NULL. is $_SERVER['UNIQUE_ID'] a
string I should hash, or an integer?

Actually, using just the first two should be sufficient, as the
pair (microtime(), getmypid()) should be unique. However, to get
more entropy, throw in some of the others.

If you are using pseudo-random numbers to select one of 100 images,
expect the same image twice in a row about 1% of the time, unless
you have code to deal with this. My suggestion is to not attempt
to avoid this.

I get a different image on next page refresh, possibly due to the time
involved. but the same images all over the page, possibly due to the time
involved.
I suppose I could use the current rancom number as the seed for the next
random number. but would that really work?


It's a very BAD idea to seed a pseudo-random number generator
multiple times in the same run. Using the output of the random
number generator as a new seed is also not a good idea. It's very
easy to cripple a good pseudo-random number generator with a poor
method of choosing a seed. The problem you're having with microtime()


I understand that. I was trying to avoid it. but nothing seems to work
short of having semaphore'd access to a file or database as the seed and
just incrementing it like a counter. And then I'm circumventing the web
server's whole concept of parallelism. :-/
demonstrates this. Seed once. Use a good source of (pseudo-)randomness.
microtime() alone doesn't qualify if you require rapid-fire results.

tell me about it. :-/
Gordon L. Burditt

Apr 23 '06 #7
>> >I need to generate 2 random numbers in rapid sequence from either PHP or
mysql.
Same page hit or different page hits? I cannot explain why you
would get the same number in rapid sequence from several calls on
the same hit.

same page hit on the webserver to a .html file, which has 2 <img
src=img.php> elements.
on a multiprocessor webserver, this may be occurring simultaneously.


Show the code for generating the two <img src= tags. Since PHP is
a procedural and uni-tasking (within any page, unless you start
calling fork()) language, these should NOT be done simultaneously,
even on a multi-processor system, although they might be done fast
enough that microtime() doesn't advance. Also show all the calls to get
random numbers and set seeds.

Are you sure you're not seeding twice with the same seed? SEED ONLY ONCE.

Look at the source HTML code. Are you getting:

- the same image number (e.g. 1) all the time?
- random first image number but the second is always the same as the first?
Things to use for a seed (jumble them all together, as in concatenate,
then take md5 of result, then convert some of md5 result to integer):
microtime()
getmypid()


believe it or not, on these 2 I get the same pictures. frustrating.


Are you running Apache 2.0? It may be using threads instead of
processes, even for PHP. Is PHP even supposed to work with Apache
2.0 yet? On a multiprocessor system?
$_SERVER['UNIQUE_ID'] (Apache only, and may need a module turned on)


Don't think I have that option. sure sounds good though.


The module name is mod_unique_id.
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PORT']
these two won't make it unique, because both images are going to be all on
the same page.
mt_srand(make_s eed()+getmypid( )+$_SERVER['UNIQUE_ID']);
$n=mt_rand(1,$r ow['a']);


Show me the code to generate the SECOND id. You don't repeat both
of those lines of code, do you? SEED ONLY ONCE!
tried this, but still doesn't do it. I don't even get an error on
$_SERVER['UNIQUE_ID']. I think it's NULL. is $_SERVER['UNIQUE_ID'] a
string I should hash, or an integer?


It's a string. Try printing it just to see if it's getting set at all.
If it is getting set, it's probably being interpreted as the integer 0
because you're trying to use it as a number.

Please verify your code:

1) There is at most one call to microtime() in any of the files used
by this page. This call is NOT inside a function. More specifically,
this call is NOT inside make_seed(). Delete that function and
expand it in line (ONCE) if desired.
2) There is at most one call to any function to set a seed (srand,
mt_srand). This call is NOT inside a function.

Gordon L. Burditt
Apr 23 '06 #8

"Gordon Burditt" <go***********@ burditt.org> wrote in message
news:12******** *****@corp.supe rnews.com...
I need to generate 2 random numbers in rapid sequence from either PHP or
mysql.


Same page hit or different page hits? I cannot explain why you
would get the same number in rapid sequence from several calls on
the same hit.
I have not been able to do either. I get the same number back several
times
from PHP's mt_rand() and from mysql's RAND().
any ideas?


When PHP starts up, the seed gets initialized to <SOMETHING>,
possibly based on microtime(), but I really don't care. Apache/PHP
don't get restarted very often. With a good host, it could easily
be less than once a month. However, once PHP starts, it's fixed.

It is likely that if Apache fork()s for a given hit, the seed stays
initialized to <SOMETHING> unless you explicitly set it. Any changes
to that by more calls to get pseudo-random numbers are discarded
when that instance of Apache exits. To get different values, you
need to explicitly set the seed to a function of something other
than just microtime().

Things to use for a seed (jumble them all together, as in concatenate,
then take md5 of result, then convert some of md5 result to integer):
microtime()
getmypid()
$_SERVER['UNIQUE_ID'] (Apache only, and may need a module turned on)
$_SERVER['REMOTE_ADDR']
$_SERVER['REMOTE_PORT']

Actually, using just the first two should be sufficient, as the
pair (microtime(), getmypid()) should be unique. However, to get
more entropy, throw in some of the others.

If you are using pseudo-random numbers to select one of 100 images,
expect the same image twice in a row about 1% of the time, unless
you have code to deal with this. My suggestion is to not attempt
to avoid this.
I suppose I could use the current rancom number as the seed for the next
random number. but would that really work?


It's a very BAD idea to seed a pseudo-random number generator
multiple times in the same run. Using the output of the random
number generator as a new seed is also not a good idea. It's very
easy to cripple a good pseudo-random number generator with a poor
method of choosing a seed. The problem you're having with microtime()
demonstrates this. Seed once. Use a good source of (pseudo-)randomness.
microtime() alone doesn't qualify if you require rapid-fire results.

Gordon L. Burditt


well, I have one last thing I can do. I asked about doing XML inline images
and got this really cook info. hope it would work with HTML.
echo "<img src=\"data:$mim etype;base64," .
base64_encode(f ile_get_content s($filepath)) . "\" alt=\"$alt\" width=\"$w\"
height=\"$h\" style=\"$style\ "$end>";

just insert this into a function. from http://www.ietf.org/rfc/rfc2397.txt .
calling a function to generate an imline image should allow me to use the
random number generator as it's supposed to be used. then I don't have to
use <img src="img.php">

just tried it. output looks correct, but doesn't show an image. :-(
and base64_encode() sure is slow!
Alas, I found out this only works in NS, not IE. IE requires MIME encoding,
which I've never done, and since it looks like it requires headers, I may be
back to square one problem with the seed.
Apr 23 '06 #9
Message-ID: <rf************ *************** ***@comcast.com > from Jim
Michaels contained the following:
well, I have one last thing I can do.


More than that. I've used rand() loads of times and not had a problem.

See:http://www.ckdog.co.uk/phpcourse/DICE/DICEGAME.PHP which picks two
random numbers and displays images according to what the number is.

With the code

$num=rand(1,6);
$num2=rand(1,6) ;
$total=$num+$nu m2;

$num1 and $num2 are only occasionally the same (as you might expect)
Full code here:-

http://www.ckdog.co.uk/phpcourse/DICE/dicegame.phps
--
Geoff Berrow (put thecat out to email)
It's only Usenet, no one dies.
My opinions, not the committee's, mine.
Simple RFDs http://www.ckdog.co.uk/rfdmaker/
Apr 23 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
2403
by: Wahoo | last post by:
Another question,my teacher gave me a code for generate a random number from 1 - range, but I can't made it work, where is the problem? Thanks!!
15
4946
by: John Cassidy | last post by:
This has been driving me crazy. I've done basic C in school, but my education is mainly based on object oriented design theory where Java is our tool. For some reason, while helping a friend with a C Programming lab. I cannot for the life of me generate a random number. i don't know what is wrong. please help. #include <stdio.h> #include <stdlib.h> #include <math.h>
14
9891
by: Anthony Liu | last post by:
I am at my wit's end. I want to generate a certain number of random numbers. This is easy, I can repeatedly do uniform(0, 1) for example. But, I want the random numbers just generated sum up to 1 . I am not sure how to do this. Any idea? Thanks.
6
2775
by: Anamika | last post by:
I am doing a project where I want to generate random numbers for say n people.... These numbers should be unique for n people. Two people should not have same numbers.... Also the numbers should not be repeted.. Do anyone have some nice algorithm for that? Or anyone can suggest me any type of book or site for that purpose?
7
4554
by: Brian | last post by:
Hi there I have been looking for a script that can randomly rotate 8 different images on 1 page. I used to have a script that did this but can't find it now. I have found loads of script that will load a differnet image each time the page loads, or will rotate 1 image at a time, but not one that can do 8 images from a list of images Does anybody know of one?
8
7205
by: Marc | last post by:
Hi all, I have to generate and send to a printer many 6 digit alphanumeric strings. they have to be unique but I cannot check in a database or something like that if it have already been printed. the string has also to seem a random one and it cannot have an apparence of a sequence. My first approach is to do it with a decimal counter and find and use an encryption alghorithm that converts each 6 digit decimal number to a 6 digit...
9
6605
by: Chelong | last post by:
Hi All I am using the srand function generate random numbers.Here is the problem. for example: #include<iostream> #include <time.h> int main() {
24
7223
by: pereges | last post by:
I need to generate two uniform random numbers between 0 and 1 in C ? How to do it ? I looked into rand function where you need to #define RAND_MAX as 1 but will this rand function give me uniformly distributed and unique numbers ?
17
6729
by: almurph | last post by:
Hi, Hope you can help me with this one. I am trying to create random number between 0 and 1 inclusive of cryptographiuc quality. The problems is though - I don't know how! Here is what I have so far and I would greatly appreciate any comments/suggestions/code-samples that you may like to share. Thank you. Al
0
9280
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9200
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9142
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8144
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6722
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6016
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4795
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3238
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2677
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.