PDA

View Full Version : Random without Math.random



jscheuer1
12-12-2006, 06:02 AM
I recently discovered, quite by accident, that one can create apparent randomness in a script without using Math.random. It happened because I had created an unbalanced system. The script starts out sliding 6 images into 6 divisions using the same OO script. It is an OO adaptation of a slide in slide show so, the script continues to slide in images at the same regular interval for all divisions. However, I set up a check to make sure no other image was sliding whenever a particular one was about to, if it was, the new slide would be delayed 100ms and try again. The interval was 3000ms so I figured things would just go in order but, they do not always do so and after a while appear to become quite random. I'm not concerned about this as a problem, rather as an unexpected 'feature'. I am wondering if others have or have seen other examples of this randomness in scripts without using Math.random?

ddadmin
12-12-2006, 09:15 AM
Well I do know setTimeout() and setInterval() do not always fire per the time interval you specify, probably due to system resources issues at the time of running with your computer. But how does this replace Math.random though if one needs to, say, generate a random number in JavaScript?

Twey
12-12-2006, 09:58 AM
This is known as a race condition. It's quite common in thread-based applications, and various solutions exist for it (such as mutexes).

ddadmin: it's not to do with system resources, but rather that the browser is single-threaded. Thus, if some other request is being processed at the time the timeout expires, its execution is postponed.

jscheuer1
12-12-2006, 02:20 PM
This apparent randomness does not of itself (though, with modification/clever use, might) replace generating a random number but, can replace the need for the random number to begin with. It depends upon why the random number was needed. Oftentimes, a random number is only used to generate random effects. If this is all that is desired, the number isn't required, just the effect.

Perhaps a demo is in order:

http://home.comcast.net/~jscheuer1/side/files/present_slide_oo_complete_nosync.htm

ddadmin
12-12-2006, 09:34 PM
Perhaps a demo is in order:

http://home.comcast.net/~jscheuer1/side/files/present_slide_oo_complete_nosync.htm

Very cool demo, and I'm just talking about in general! Back to how it relates to the discussion though, the only thing that's uneven in the demo for me is the delay between image changes with supposedly identical slideshow instances. Everything else looks uniform, such as the sequence of images that get slided in. What effect are you referring to as far as not requiring Math.random() to generate?

djr33
12-13-2006, 01:16 AM
That demo just proves that there is in fact a pattern behind the "randomness". While the images appear, after a few minutes, to be at random, watching the script progress from the beginning and careful inspection of several images in a row as it continues shows a clear and defined pattern, in which one step in the rotation is skipped every few times dependant on what the browser is currently occupied with.

If you scramble a number several times, you could call that "random". In fact, any random function does just that, so this is just an example of a way to fake a PSEDUO-random number. (Or, I suppose, event.)

The main problem that I see with it's use is the repetition involved. One could, I suppose, run the function several hundred times and hope for a randomized result, but that seems innefficient. Additionally, I also wonder if there is anything actually random about the script at all, since it might do the same exact thing each time. For example, md5 is a very complex algorithm that generates what looks like it must be random, but there is a method to the madness, as there would be here.

Perhaps you should write a test page that cycles through a similar function say 1000 times then outputs the value (or pictures, whatever), and we can see if it is, as I suspect, the same, or at least the same on many occasions.

jscheuer1
12-13-2006, 05:29 AM
Very cool demo, and I'm just talking about in general! Back to how it relates to the discussion though, the only thing that's uneven in the demo for me is the delay between image changes with supposedly identical slideshow instances. Everything else looks uniform, such as the sequence of images that get slided in. What effect are you referring to as far as not requiring Math.random() to generate?

Thanks on the demo. I just put it up mostly as I had made it, without ever intending it to be random. The only change I made was to allow this 'random' behavior in IE. Originally, I was only caching slide instances in other browsers as, IE is capable of doing 6 at once smoothly. So is Opera but, I hadn't realized that at first. FF got rough even with two at once.

On to a further explanation of the randomness. If you reload the browser, you will probably get different results than a first time through. Especially if you occasionally clear the cache. This is due to the fact that this script is also written to not start a given sliding slide show until all of its images are preloaded (a slightly different thing than cached but, using the cache). What this does is introduce different start times. That could be hard coded though, as could different intervals.

Anyways, my object wasn't to create an unstable system but, that is what happened, at least somewhat. My point is that one could probably create an even more unstable system intentionally and get even more striking results. On occasion, if you let the thing run long enough, it gets really random. It will go along in a groove for awhile but then, sometimes, devolves into what looks like total randomness.

My question was, "Has anyone seen or written other scripts that do this, without using Math.random?"

djr33
12-13-2006, 05:49 AM
I haven't seen anything like it.

The problem, as I said above, is that for this to work, you need to allow the script to run for some time before it really becomes 'random'.

jscheuer1
12-13-2006, 05:52 AM
There is no problem djr33, we are discussing a phenomenon.

djr33
12-13-2006, 07:31 AM
A phenomenon is by definition unexplained. Single threated processes explain this.

jscheuer1
12-13-2006, 07:58 AM
A phenomenon is by definition unexplained.

What dictionary did you find that in? I like this definition from Merriam-Webster 2006:


1 plural phenomena : an observable fact or event
2 plural phenomena a : an object or aspect known through the senses rather than by thought or intuition b : a temporal or spatiotemporal object of sensory experience as distinguished from a noumenon c : a fact or event of scientific interest susceptible to scientific description and explanation
3 a : a rare or significant fact or event b plural phenomenons : an exceptional, unusual, or abnormal person, thing, or occurrence

Anyways, I've adjusted one factor in the demo and it is even more readily apparent what I am talking about. Still no Math.random.

ddadmin
12-13-2006, 09:35 AM
Anyways, I've adjusted one factor in the demo and it is even more readily apparent what I am talking about. Still no Math.random.

I see what you mean as far as the delay between image changes now being completely off between identical slideshow instances. Twey talked about setTimeout/ setInterval being unpredictable due to the browser being single threaded- I wonder if that means a multi-threaded browser (whatever that means) is required to run multiple instances of the same script in perfect sync?

But I think you hit the nail in the head on the other possible culprit, which is that your slideshows are set to run only after the images have been "preloaded." Theoretically 2 slideshow instances should mean the 2nd instance should take virtually no time to preload the images, but who knows what each browser actually does under the hood. If this was the only problem I think it probably can be overcome by some "clever" coding. In any event, I think this type of randomness is almost always undesired- are you trying to "harness" it somehow John? :)

jscheuer1
12-13-2006, 03:01 PM
DD and djr33,

You both seem to want to help me fix this 'problem', understandable given the nature of the forums here but, I didn't open this thread to get this thing fixed.

Still, from the beginning, this bit of script took on a life of its own to a degree so, any suggestions are welcome. I do already have a method of doing this same basic script that controls the output in such a way that the sliding always follows a particular order though.

And, yes, I am looking for other ways to harness this. Randomness shouldn't be all that hard to script without resorting to Math.random. Randomness is actually the natural state of things. Programming languages are built upon the premise, unmentioned or otherwise, of creating order and events that are identical, easily duplicated. But, this doesn't have to be the result.

"It's Alive!"

- Mary Shelly

Twey
12-13-2006, 03:49 PM
I wonder if that means a multi-threaded browser (whatever that means) is required to run multiple instances of the same script in perfect sync?A single processor can only process one instruction at once. Timeslices are allocated to various processes by the kernel to make it seem as if the computer is running multiple processes at the same time, but in truth it just switches between them too fast for us to follow. As such, no two processes on a single-CPU machine will ever run exactly in sync. However, usually it can be approximated, since the two processes can be given equal timeslices so that by the time the later process has finished... well, processing... it's at the same state as the earlier. Browsers (or at least their scripting engines) don't take advantage of this time-slicing thing. For example, if a browser is provided with the code:
setTimeout(doSomething, 100);
var startDate = (new Date()).getTime();
while((new Date()).getTime() - startDate < 10000) {}(which, incidentally, I don't recommend), doSomething() will not be executed for ten seconds. The timeout is set, but then the script moves on to processing that for loop for ten seconds, and doesn't call the function until there's nothing else to do.

mwinter
12-13-2006, 05:10 PM
Twey talked about setTimeout/ setInterval being unpredictable due to the browser being single threaded

It's more than that. Timer resolution is relatively poor. At best, recent operating systems provide around 10ms, but older systems (like Window 98) have a far lower resolution: around 55ms. There's also general scheduling competition, as Twey described.



I wonder if that means a multi-threaded browser (whatever that means) is required to run multiple instances of the same script in perfect sync?

All browsers are multi-threaded, but rendering a single document, as well as executing scripts in that document, is always performed in a single thread. As scripts can modify the document at any time, and multiple times in separate operations, it wouldn't make much sense to try and do everything concurrently. It would be wasted effort.

Mike

jscheuer1
12-13-2006, 09:51 PM
All browsers are multi-threaded, but rendering a single document, as well as executing scripts in that document, is always performed in a single thread. As scripts can modify the document at any time, and multiple times in separate operations, it wouldn't make much sense to try and do everything concurrently. It would be wasted effort.

Mike

I wonder if this is true of IE 6+ running on Windows XP. The script handling is so smooth, it seems as though it is multi-threading right on the page. I'm not saying that it is, just wondering.

mwinter
12-14-2006, 12:50 AM
I wonder if this is true of IE 6+ running on Windows XP. The script handling is so smooth, it seems as though it is multi-threading right on the page. I'm not saying that it is, just wondering.

I doubt it. Aside from specific host objects, like the one implementing the IXMLHTTPRequest interface, I've not observed script behaviour that suggests concurrency. Quite the opposite, in fact. Even in that case, it's the ActiveX component that is multi-threaded, not the JScript engine.

Remember that IE can be made to be more efficient than other browsers: Microsoft don't need to make the effort to support non-Windows operating systems and graphical subsystems. Browsers such as Opera and Firefox do, and as I recall, they use toolkits to accomplish that.

Mike

djr33
12-14-2006, 04:33 AM
DD and djr33,

You both seem to want to help me fix this 'problem',
No, I just think this is silly.
Yes, it's a way to fake something that seems random, but it relies on the browser calculating something a large number of times to really get there, so it seems inefficient.
Sure, you could replace math.random with this, but isn't the point of programming to use the fewest system resources?
This might give the same result, but surely it isn't less resource-demanding that math.random...?
And, I don't know about the theory by itself, but your demo page didn't work in Safari, just IE/Mozilla (didn't test opera, etc.), so I would assume that math.random may be a lot more compatible.

Additionally, isn't this just relying upon an error? If a system were powerful enough or setup to handle this, wouldn't this work 'correctly' and not be random?

jscheuer1
12-14-2006, 05:05 AM
it relies on the browser calculating something a large number of times to really get there, so it seems inefficient.

I'm not sure if this is true, could you reproduce the effect using Math.random? If so, could you do it as, or more economically, code wise?

Also, any incompatibility with Safari is probably not due to the randomness. What's the problem in that browser?

The script most likely works (if you are willing to count its fall back execution) in IE 4+ and NS 6+ and Opera 7+. Tested in IE 7, FF 1.5.0.8 and Opera 9.01.

jscheuer1
12-14-2006, 05:17 AM
I doubt it. . . .

Remember that IE can be made to be more efficient than other browsers: Microsoft don't need to make the effort to support non-Windows operating systems and graphical subsystems. Browsers such as Opera and Firefox do, and as I recall, they use toolkits to accomplish that.

Mike

I was thinking that might be it. Opera seems to be getting better at executing scripts in the Windows environment, while FF appears (this is just in my experience) to be standing still in this area.

djr33
12-14-2006, 05:21 AM
In Safari, nothing showed up. As I said above, it may very well have to do with the rest of the script.
However, I still would guess math.random is more compatible.


The issue isn't about shorter code, but about system resources. Doesn't this, due to basically overloading the system, use a lot more memory/processing power than just using math.random?

jscheuer1
12-14-2006, 05:36 AM
The whole page takes 1MB (or less) each page file and physical. Small, I would think, for a dynamic web page with many images.

djr33
12-14-2006, 05:50 AM
Hmm... alright.

Whatever, no big deal. Just seems a bit odd that it's such a big deal.

jscheuer1
12-14-2006, 06:09 AM
In Safari, nothing showed up.

Well, did you try it in Safari since I first posted about this? I tightened up the code since then. Also, doesn't Safari ever give any errors in situations like that?