By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,624 Members | 1,597 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,624 IT Pros & Developers. It's quick & easy.

Whats wrong with this?

P: n/a
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Math.random());
document.write(safetyTips[i]);
}
output();
//-->
</script>
safetyTips[] - this array is in here.js ...

Jul 23 '05 #1
Share this Question
Share on Google+
62 Replies


P: n/a
TheShadow1 wrote on 02 apr 2005 in comp.lang.javascript:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Math.random());
document.write(safetyTips[i]);
}
output();
//-->
</script>


You cannot have both an external and inline scripting
with the same <script> block.

Don't use <!--, //-->, outdated for years.

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #2

P: n/a
TheShadow1 wrote:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Math.random());
document.write(safetyTips[i]);
}
output();
//-->
</script>

safetyTips[] - this array is in here.js ...


Evertjan has already fixed your main problem, but you also have given
yourself a maintenance problem by hard-coding (I presume) the length
of your array.

Given the general nature of the question in your subject, I'll add
that you can also make it more concise (I've used 'sT' for the name
of the safteyTips array to avoid wrapping):

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write(sT[Math.round((sT.length-1)*Math.random())]);
</script>

is all that is required.

--
Rob
Jul 23 '05 #3

P: n/a
Lee
RobG said:

TheShadow1 wrote:
<script type="text/JavaScript" src="here.js">
<!--
function output() {
var i = Math.round(5*Math.random());
document.write(safetyTips[i]);
}
output();
//-->
</script>

safetyTips[] - this array is in here.js ...


Evertjan has already fixed your main problem, but you also have given
yourself a maintenance problem by hard-coding (I presume) the length
of your array.

Given the general nature of the question in your subject, I'll add
that you can also make it more concise (I've used 'sT' for the name
of the safteyTips array to avoid wrapping):

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write(sT[Math.round((sT.length-1)*Math.random())]);


Using Math.round() underselects the first and last elements of the array.
sT[Math.floor(Math.random()*sT.length)]

Jul 23 '05 #4

P: n/a
RobG <rg***@iinet.net.auau> writes:
document.write(sT[Math.round((sT.length-1)*Math.random())]); .... is all that is required.


Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math.random() * sT.length)]
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #5

P: n/a
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.net.auau> writes:

document.write(sT[Math.round((sT.length-1)*Math.random())]);


...
is all that is required.

Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math.random() * sT.length)]

or:
sT[new Date()%sT.length]

Mick
Jul 23 '05 #6

P: n/a
Lee wrote:
RobG said:

[...]

<script type="text/javascript" src="here.js"></script>
<script type="text/javascript">
document.write(sT[Math.round((sT.length-1)*Math.random())]);

Using Math.round() underselects the first and last elements of the array.
sT[Math.floor(Math.random()*sT.length)]


I was going to comment on the possibility that the selection was not
even for all elements in the array, however using Math.floor as
suggested infers that Math.random will *never* return 1, or at least
that the index will never be evaluated to be the length of the array.

Should that occur, the tip of the day will be 'undefined'.

The specification says that Math.random will return a value "greater
than or equal to 0 but less than 1" which means that in theory the
.floor method is OK, but is it in practice?
--
Rob
Jul 23 '05 #7

P: n/a
RobG wrote:
Lee wrote:

<snip>
Using Math.round() underselects the first and last elements of the
array. sT[Math.floor(Math.random()*sT.length)]


I was going to comment on the possibility that the selection was not
even for all elements in the array, however using Math.floor as
suggested infers that Math.random will *never* return 1, or at least
that the index will never be evaluated to be the length of the
array.

Should that occur, the tip of the day will be 'undefined'.

The specification says that Math.random will return a value "greater
than or equal to 0 but less than 1" which means that in theory the
.floor method is OK, but is it in practice?


Apparently a now every old Opera version (I think it was 4 but it may
have been 5) had a buggy Math.random that did occasionally return 1. I
have not heard mention of any other javascript versions with the same
problem. Absolute safety can be guaranteed with - Math.random() % 1 -.

A faster alternative to Math.floor in this context could be an OR zero
operation:-

array.sT[((Math.random()*sT.length) | 0)]

As OR zero truncates numbers with fractional parts into integers. It
also restricts the possible range of those integers to 32 bit signed
integers, which is half of the specified possible range for Array
indexes (though that should not be a problem in most cases).

Richard.
Jul 23 '05 #8

P: n/a
JRS: In article <nG****************@twister.nyroc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.net.auau> writes:

document.write(sT[Math.round((sT.length-1)*Math.random())]);


...
is all that is required.

Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math.random() * sT.length)]

or:
sT[new Date()%sT.length]


I think that the OP has a 5-element array.
Have you tried your method with 5 or 10 elements in the array?
Actually, AFAIK, it *might* work in XP, and *might* in non-PC; but I
don't expect it to in NT, and it does not in Win98.

Do any systems show a 1 ms resolution for X = new Date() ?

<FAQENTRY> :

I find that
(Math.random()*10)|0
is appreciably faster than
Math.floor(Math.random()*10)
although the latter might be considered more readable.

If tests on other systems show similar results, ISTM that it would be
worth adding the former to FAQ 4.22, and taking the opportunity to
remark that |0 can beat Math.floor.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #9

P: n/a
Dr John Stockton wrote:
JRS: In article <nG****************@twister.nyroc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :
Lasse Reichstein Nielsen wrote:
RobG <rg***@iinet.net.auau> writes:

document.write(sT[Math.round((sT.length-1)*Math.random())]);

...
is all that is required.
Don't use Math.round like this, it gives the first and last element
only half the chance of the others.

Use:

sT[Math.floor(Math.random() * sT.length)]
or:
sT[new Date()%sT.length]

I think that the OP has a 5-element array.
Have you tried your method with 5 or 10 elements in the array?
Actually, AFAIK, it *might* work in XP, and *might* in non-PC; but I
don't expect it to in NT, and it does not in Win98.

Well, John, new Date() is cast as a Number in a Modulus operation.

sT[new Date().getTime()%sT.length] will force the conversion though, and
create equal distribution of the array entries. Since the datestamp is a
large dynamic number, its use is ideal in this scenario (one off).
I don't know why it wouldn't work in NT or Win98, please educate me.
Mick

Do any systems show a 1 ms resolution for X = new Date() ?
<FAQENTRY> :

I find that
(Math.random()*10)|0
is appreciably faster than
Math.floor(Math.random()*10)
although the latter might be considered more readable.

If tests on other systems show similar results, ISTM that it would be
worth adding the former to FAQ 4.22, and taking the opportunity to
remark that |0 can beat Math.floor.

Jul 23 '05 #10

P: n/a
Mick White <mw***********@rochester.rr.com> writes:

Well, John, new Date() is cast as a Number in a Modulus operation.
Correct.
sT[new Date().getTime()%sT.length] will force the conversion though,
and create equal distribution of the array entries.
Force conversion, yes. Guarantee equal distribution ... no.
Since the datestamp is a large dynamic number, its use is ideal in
this scenario (one off). I don't know why it wouldn't work in NT or
Win98, please educate me.


Because the granularity of the millisecond counter isn't necessarily
as small as you hope. What if the counter incremented exactly once
every 10ms? Then doing new Date()%5 would not be very random.

In a simple test (both IE 6 and Opera 8 on WinXP/SP2) I found the
result of new Date()%10 to be scewed, with 4 and 9 having only half
the frequency of the other results.

In fact, the values of new Date().getTime() seems to increment in steps
of 15 or 16 (the increases appears to repeat the sequence
15 16 15 16 16 15 16 16
i.e., eight increases in 125 ms).

So, the answer is that Date is simply not random enough.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #11

P: n/a
Lasse Reichstein Nielsen wrote:
Mick White <mw***********@rochester.rr.com> writes: [..]
Since the datestamp is a large dynamic number, its use is ideal in
this scenario (one off). I don't know why it wouldn't work in NT or
Win98, please educate me.

Because the granularity of the millisecond counter isn't necessarily
as small as you hope. What if the counter incremented exactly once
every 10ms? Then doing new Date()%5 would not be very random.

In a simple test (both IE 6 and Opera 8 on WinXP/SP2) I found the
result of new Date()%10 to be scewed, with 4 and 9 having only half
the frequency of the other results.

In fact, the values of new Date().getTime() seems to increment in steps
of 15 or 16 (the increases appears to repeat the sequence
15 16 15 16 16 15 16 16
i.e., eight increases in 125 ms).

So, the answer is that Date is simply not random enough.
/L


Thanks for the response, Lasse, my own test doesn't appear to support
your assertion.

http://home.rochester.rr.com/mickweb...pt/random.html

Where I display new Date()%10 at 250 random intervals of one second or less.

Methodology flawed?
Mick


Jul 23 '05 #12

P: n/a
Mick White wrote:
Lasse Reichstein Nielsen wrote:
Mick White <mw***********@rochester.rr.com> writes:


[..]
Since the datestamp is a large dynamic number, its use is ideal in
this scenario (one off). I don't know why it wouldn't work in NT or
Win98, please educate me.


Because the granularity of the millisecond counter isn't necessarily
as small as you hope. What if the counter incremented exactly once
every 10ms? Then doing new Date()%5 would not be very random.

In a simple test (both IE 6 and Opera 8 on WinXP/SP2) I found the
result of new Date()%10 to be scewed, with 4 and 9 having only half
the frequency of the other results.

In fact, the values of new Date().getTime() seems to increment in steps
of 15 or 16 (the increases appears to repeat the sequence 15 16 15 16
16 15 16 16
i.e., eight increases in 125 ms).

So, the answer is that Date is simply not random enough.
/L

Thanks for the response, Lasse, my own test doesn't appear to support
your assertion.

http://home.rochester.rr.com/mickweb...pt/random.html

Where I display new Date()%10 at 250 random intervals of one second or
less.

Methodology flawed?


The flaw is expecting an even distribution of values from date() but
there is nothing in the ECMA specification that says that must occur.
The value of a newly constructed Date object is specified as "the
current time" which should be a number indicating a particular
instant in time to within a millisecond. There is no accuracy [1]
or distribution criterion.

On the other hand, the specification states that random() should have
an approximately uniform distribution. While that does not guarantee
an even distribution, it is more likely to provide one across all
systems than date() (or so testing would appear to show, at least in
my case).

Running the date-based random number selector on my PC gave a
significant and consistent over-representation to some values - 2, 4,
7 & 9 were about half as likely to occur as the other values.
Removing the randomisation of the interval did not change the results
(but they happen much faster!)

Replacing: d = new Date()%10

with JRS's: d = (Math.random()*10)|0;

produced a more even distribution over a number of tests, though
typically one value was the mode far more frequently than any other.

Code posted below.

1. To my understanding, accuracy relates to how close a measurement is
to the true value; precision relates to the repeatability of a
measurement. So it is possible to have precise measurements that
are not accurate.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head><title>Random?</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<style type="text/css">
body {background-color: #FFFFFF;}
td {/* font-family: "Courier New", Courier, mono; */
font-size: 80%; border: 1px solid green;}
table {border-collapse: collapse; padding: 0;}
</style></head>
<body>
<script type="text/JavaScript">
function R(f){
var t = f.timerand[0].checked;
document.getElementById('tType').innerHTML = (t)?'time':'random';
var mod = f.modulus.value;
var tb = document.getElementById('tbA');
var oR, oT, i = 0, times = 0;
do {
if (!document.getElementById('f'+i)) {
oR = document.createElement('TR');
oT = document.createElement('TD');
oT.appendChild(document.createTextNode(i));
pT = document.createElement('TD');
pT.id = "f"+i;
oR.appendChild(oT);
oR.appendChild(pT);
tb.appendChild(oR);
}
} while (++i < mod)

while (times++ < 1000) {
d = (t)? new Date()% mod : (Math.random()*mod)|0;
document.getElementById("f"+d).innerHTML += '' + '.';
document.getElementById("test").innerHTML = ++times;
}
var count = document.getElementById("count").innerHTML;
document.getElementById("count").innerHTML = +count + times-1;
}
</script>
<form action="">
<input type="radio" name="timerand" value="time" checked>
Use time<br>
<input type="radio" name="timerand" value="random">
Use random<br>
<input type="text" name="modulus" value="10" size="5">modulus<br>
<input type="button" value="Run test" onclick="
R(this.form);
"><br>
<input type="reset">
</form>
<p><span id="test"></span> of <span id="count"></span>
using <span id="tType"></span></p>
<table>
<tbody id="tbA">
</tbody>
</table>
</body>
</html>


--
Rob
Jul 23 '05 #13

P: n/a
RobG wrote:
Mick White wrote:
Lasse Reichstein Nielsen wrote:
Mick White <mw***********@rochester.rr.com> writes:

[..]

Since the datestamp is a large dynamic number, its use is ideal in
this scenario (one off). I don't know why it wouldn't work in NT or
Win98, please educate me.


Because the granularity of the millisecond counter isn't necessarily
as small as you hope. What if the counter incremented exactly once
every 10ms? Then doing new Date()%5 would not be very random.

In a simple test (both IE 6 and Opera 8 on WinXP/SP2) I found the
result of new Date()%10 to be scewed, with 4 and 9 having only half
the frequency of the other results.

In fact, the values of new Date().getTime() seems to increment in steps
of 15 or 16 (the increases appears to repeat the sequence 15 16 15
16 16 15 16 16
i.e., eight increases in 125 ms).

So, the answer is that Date is simply not random enough.
/L


Thanks for the response, Lasse, my own test doesn't appear to support
your assertion.

http://home.rochester.rr.com/mickweb...pt/random.html

Where I display new Date()%10 at 250 random intervals of one second or
less.

Methodology flawed?

The flaw is expecting an even distribution of values from date() but
there is nothing in the ECMA specification that says that must occur.
The value of a newly constructed Date object is specified as "the
current time" which should be a number indicating a particular
instant in time to within a millisecond. There is no accuracy [1]
or distribution criterion.

On the other hand, the specification states that random() should have
an approximately uniform distribution. While that does not guarantee
an even distribution, it is more likely to provide one across all
systems than date() (or so testing would appear to show, at least in
my case).

Running the date-based random number selector on my PC gave a
significant and consistent over-representation to some values - 2, 4,
7 & 9 were about half as likely to occur as the other values.
Removing the randomisation of the interval did not change the results
(but they happen much faster!)

Replacing: d = new Date()%10

with JRS's: d = (Math.random()*10)|0;

produced a more even distribution over a number of tests, though
typically one value was the mode far more frequently than any other.

Code posted below.

1. To my understanding, accuracy relates to how close a measurement is
to the true value; precision relates to the repeatability of a
measurement. So it is possible to have precise measurements that
are not accurate.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html><head><title>Random?</title>
<meta http-equiv="Content-Type"
content="text/html; charset=iso-8859-1">
<style type="text/css">
body {background-color: #FFFFFF;}
td {/* font-family: "Courier New", Courier, mono; */
font-size: 80%; border: 1px solid green;}
table {border-collapse: collapse; padding: 0;}
</style></head>
<body>
<script type="text/JavaScript">
function R(f){
var t = f.timerand[0].checked;
document.getElementById('tType').innerHTML = (t)?'time':'random';
var mod = f.modulus.value;
var tb = document.getElementById('tbA');
var oR, oT, i = 0, times = 0;
do {
if (!document.getElementById('f'+i)) {
oR = document.createElement('TR');
oT = document.createElement('TD');
oT.appendChild(document.createTextNode(i));
pT = document.createElement('TD');
pT.id = "f"+i;
oR.appendChild(oT);
oR.appendChild(pT);
tb.appendChild(oR);
}
} while (++i < mod)

while (times++ < 1000) {
d = (t)? new Date()% mod : (Math.random()*mod)|0;
document.getElementById("f"+d).innerHTML += '' + '.';
document.getElementById("test").innerHTML = ++times;
}
var count = document.getElementById("count").innerHTML;
document.getElementById("count").innerHTML = +count + times-1;
}
</script>
<form action="">
<input type="radio" name="timerand" value="time" checked>
Use time<br>
<input type="radio" name="timerand" value="random">
Use random<br>
<input type="text" name="modulus" value="10" size="5">modulus<br>
<input type="button" value="Run test" onclick="
R(this.form);
"><br>
<input type="reset">
</form>
<p><span id="test"></span> of <span id="count"></span>
using <span id="tType"></span></p>
<table>
<tbody id="tbA">
</tbody>
</table>
</body>
</html>


Nice work, Rob, and I see the efficacy of the built-in random number
generator vis a vis that of the Date object. The differences appear to
be slight, and the outputs could use some statistical analysis.
But I'm convinced (well, almost).

Mick
Jul 23 '05 #14

P: n/a
In article <RU**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> writes
JRS: In article <nG****************@twister.nyroc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :
<snip>
or:
sT[new Date()%sT.length]


My system's Date objects supply about 19 different values per second, so
the millisecond values are unlikely to be random enough to be useful.
<snip>Do any systems show a 1 ms resolution for X = new Date() ?

<snip>

I expect there are, but they needn't be PCs.

John
--
John Harris
Jul 23 '05 #15

P: n/a
John G Harris wrote:
In article <RU**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> writes
JRS: In article <nG****************@twister.nyroc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :

<snip>
or:
sT[new Date()%sT.length]

My system's Date objects supply about 19 different values per second, so
the millisecond values are unlikely to be random enough to be useful.


You're kidding me, right?
Mick
Jul 23 '05 #16

P: n/a
Mick White wrote:
John G Harris wrote:

<snip>
My system's Date objects supply about 19 different values per
second, so the millisecond values are unlikely to be random
enough to be useful.


You're kidding me, right?


Why don't you take this seriously? It is known that the timer tick
interval on Windows 95/98 was about 54 milliseconds, and that gives
about 19 values per second.

Richard.
Jul 23 '05 #17

P: n/a
Richard Cornford wrote:
Mick White wrote:
John G Harris wrote:


<snip>
My system's Date objects supply about 19 different values per
second, so the millisecond values are unlikely to be random
enough to be useful.


You're kidding me, right?

Why don't you take this seriously? It is known that the timer tick
interval on Windows 95/98 was about 54 milliseconds, and that gives
about 19 values per second.

Richard.

At the risk of beating a dead horse,I'd day it's random enough for a
one-off.
Mick

Jul 23 '05 #18

P: n/a
JRS: In article <VR****************@twister.nyroc.rr.com>, dated Sun, 3
Apr 2005 14:13:09, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :
I think that the OP has a 5-element array.
Have you tried your method with 5 or 10 elements in the array?
Actually, AFAIK, it *might* work in XP, and *might* in non-PC; but I
don't expect it to in NT, and it does not in Win98.
Well, John, new Date() is cast as a Number in a Modulus operation.


Granted.
sT[new Date().getTime()%sT.length] will force the conversion though, and
create equal distribution of the array entries. Since the datestamp is a
large dynamic number, its use is ideal in this scenario (one off).
I don't know why it wouldn't work in NT or Win98, please educate me.
Because in Win98, or at least in my Win98 + MSIE4, the "new Date()"
number of milliseconds (incremented at 18.2 Hz) is always divisible by
10. And I think that in WinNT and some other systems it is incremented
at 100 Hz and always divisible by 10. Read my javascript Web pages, and
my pas-time.htm.
Do any systems show a 1 ms resolution for X = new Date() ?



Donald E Knuth :-
"Random numbers should not be generated with a method chosen at random".

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #19

P: n/a
JRS: In article <KW**************@jgharris.demon.co.uk>, dated Tue, 5
Apr 2005 15:38:24, seen in news:comp.lang.javascript, John G Harris
<jo**@nospam.demon.co.uk> posted :
In article <RU**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> writes
JRS: In article <nG****************@twister.nyroc.rr.com>, dated Sat, 2
Apr 2005 19:48:35, seen in news:comp.lang.javascript, Mick White
<mw***********@rochester.rr.com> posted :
<snip>
or:
sT[new Date()%sT.length]


My system's Date objects supply about 19 different values per second, so
the millisecond values are unlikely to be random enough to be useful.


Win98 or similar, I guess. The value increases 0x1800B0 times per
nominal day, being derived from the DOS $0040:$006C timer, which is near
to 18.2 Hz (obtained by division of a NTSC frequency). But the value of
milliseconds that I see, which matches what the applicable DOS interrupt
returns, is *always* divisible by 10 (and therefore is futile for
generating randoms by %10).

But if the OP were to do new Date()/10%10 then the results on Win98
should be good enough for his purpose - likewise AFAICS on other
systems. And new Date().getSeconds()%10 should also do, for him.

I've heard that on some systems, while it is still divisible by 10,
there is a true resolution of 10 ms in new Date().

When I ask what other behaviours are seen in which systems, I get no
solid answers. Someone must know something!
<snip>
Do any systems show a 1 ms resolution for X = new Date() ?

<snip>

I expect there are, but they needn't be PCs.



If a single "random" number is wanted, it should look equi-probable on
repeated testing.

If a sequence of "random" numbers is wanted, they should look equi-
probable but there should also be no evident correlation between the
N'th number and its predecessors.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #20

P: n/a
JRS: In article <oO****************@news.optus.net.au>, dated Mon, 4
Apr 2005 03:48:36, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> posted :

The flaw is expecting an even distribution of values from date() but
there is nothing in the ECMA specification that says that must occur.
The value of a newly constructed Date object is specified as "the
current time" which should be a number indicating a particular
instant in time to within a millisecond. There is no accuracy [1]
or distribution criterion.
The result must indeed be an integer number of milliseconds since
1970-01-01 00:00:00 GMT; the representation enforces that. Otherwise,
there is no more than a hope that it is as accurate as the supporting
system and system calls permit.

On the other hand, the specification states that random() should have
an approximately uniform distribution. While that does not guarantee
an even distribution, it is more likely to provide one across all
systems than date() (or so testing would appear to show, at least in
my case).


Given that efficient algorithms for reasonably random numbers of even
distribution have been known and used in computers for many years,
however, there can be no excuse for Math.random() (etc.) having anything
other than a flat distribution (i.e. as good as a true random, or
flatter) with at least 2^32 possible values. This in js-randm.htm
estimates the resolution, by assuming that all unresolved bits are
always zero :-

function Resol() { var j, X, T, M = 0
for (j = 0 ; j < 100 ; j++) { X = Math.random()
T = 0 ; while ((X*=2)%1 > 0) T++ ; if (T>M) M = T }
document.write("to be<tt> ", M, " <\/tt>bits") }

My system gives 53 bits, the limit using IEEE Doubles.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #21

P: n/a
JRS: In article <1x**********@hotpop.com>, dated Sun, 3 Apr 2005
17:09:44, seen in news:comp.lang.javascript, Lasse Reichstein Nielsen
<lr*@hotpop.com> posted :

Because the granularity of the millisecond counter isn't necessarily
as small as you hope. What if the counter incremented exactly once
every 10ms? Then doing new Date()%5 would not be very random.
The frequency of the increment matters less than the amount of the
increment. In my system, the increment is always 50 or 60.

In a simple test (both IE 6 and Opera 8 on WinXP/SP2) I found the
result of new Date()%10 to be scewed, with 4 and 9 having only half
the frequency of the other results.

In fact, the values of new Date().getTime() seems to increment in steps
of 15 or 16 (the increases appears to repeat the sequence
15 16 15 16 16 15 16 16
i.e., eight increases in 125 ms).

If that is truly incrementing at 64 Hz (as seems possible), then the
long-term distribution should be 8 6 6 6 6 8 6 6 6 6 for 0-9, if it
started at exactly X seconds. If it is close to 64 Hz, perhaps a longer
test is really needed.
So, the answer is that Date is simply not random enough.


For the OP's purpose, it is, provided that one does not use the
milliseconds decimal digit.

The first thing is to establish the range of increment rates and
resolutions across "all" systems.

This, from js-date0.htm, estimates the increment rate and numeric
resolution :-
function HCF(u, v) { var U = u, V = v // DM ; cf hcfactors.pas
while (true) {
if ((U%=V) == 0) return V
if ((V%=U) == 0) return U } }

function Resol() {
var J = 0, T0 = XT = T = new Date().getTime(), A = [], F
while (J < 10) {
if (T != XT) { A[A.length] = XT = T ; J++ }
T = new Date().getTime() }
F = A[0] ; for (J=1 ; J<A.length ; J++) F = HCF(F, A[J])
document.write(
" about<tt> ", (new Date()-T0)/10, " ms interval ",
" with numeric resolution ", F, " ms <\/tt>") }
The page includes :- But I think I've seen evidence for 1 ms in
IE6/Win2K. And a hint of 15.625 ms in dual-processor Windows.

Your figures show, of course, increment at about 15.625 ms with
resolution of 1 ms.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #22

P: n/a
Evertjan. wrote:
<snip>
Don't use <!--, //-->, outdated for years.


What's the disadvantage of this notation?

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #23

P: n/a
Lee
Stewart Gordon said:

Evertjan. wrote:
<snip>
Don't use <!--, //-->, outdated for years.


What's the disadvantage of this notation?


It serves no purpose and is a potential source of typographical errors.

Jul 23 '05 #24

P: n/a
Lee wrote:
Stewart Gordon said:
Evertjan. wrote:
<snip>
Don't use <!--, //-->, outdated for years.
What's the disadvantage of this notation?


It serves no purpose


That's not a disadvantage.
and is a potential source of typographical errors.


So is just about every aspect of HTML, JS and even human language.

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #25

P: n/a
Stewart Gordon wrote on 06 apr 2005 in comp.lang.javascript:
Lee wrote:
Stewart Gordon said:
Evertjan. wrote:
<snip>

Don't use <!--, //-->, outdated for years.

What's the disadvantage of this notation?


It serves no purpose


That's not a disadvantage.
and is a potential source of typographical errors.


So is just about every aspect of HTML, JS and even human language.


The AND should not and cannot be disregarded.

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Jul 23 '05 #26

P: n/a
Stewart Gordon wrote:
Evertjan. wrote:
<snip>
Don't use <!--, //-->, outdated for years.


What's the disadvantage of this notation?


You could have asked Google before posting, we had this many times before.

So, why the "don't" above?

You waste disk space and bandwidth ;-) Seriously, here are two Worst Cases:

You use this in a HTML document and since the content of the `script'
element is CDATA it is passed "as is" to the script engine which will
yield a script error since `<', `!' and `--' are operators (without
proper operand here).

You use this in an XHTML document and the whole script is disregarded since
a XML parser may (and most, including Gecko's will) remove comments before
building the parse tree (empty `script' element).
HTH

PointedEars
--
A true translation needs neither omissions nor addings.
It is its own content.
-- me, 2003
Jul 23 '05 #27

P: n/a
Lee
Stewart Gordon said:

Lee wrote:
Stewart Gordon said:
Evertjan. wrote:
<snip>

Don't use <!--, //-->, outdated for years.

What's the disadvantage of this notation?


It serves no purpose


That's not a disadvantage.
and is a potential source of typographical errors.


So is just about every aspect of HTML, JS and even human language.


Any aspect of HTML, JS, and even human language that is a potential
source of error and which serves no purpose, is a net negative and
should be avoided.

Jul 23 '05 #28

P: n/a
JRS: In article <d2*******************@news.demon.co.uk>, dated Wed, 6
Apr 2005 01:16:30, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
Mick White wrote:
John G Harris wrote:

<snip>
My system's Date objects supply about 19 different values per
second, so the millisecond values are unlikely to be random
enough to be useful.


You're kidding me, right?


Why don't you take this seriously? It is known that the timer tick
interval on Windows 95/98 was about 54 milliseconds, and that gives
about 19 values per second.


Come off it - "was" - no, here, it still is. Better figures are 55, or
54.9, ms and 18.2 Hz.
18.2 Hz is actually 0x1800B0/86400 or 18.206481481481482; the interval
is 0.054925494583735954 s - and those are exact to the extent that the
system time-of-day clock puts exactly 24 h in each normal day.

Starting with F=14.31818 MHz (315/22 MHz) as on ISA bus 30B; F/12 =
1.193182 MHz; F/3 = 4.77 MHz, the original PC clock frequency, and F/4 =
3.579545 MHz, the US NTSC TV "color sub-carrier" frequency, used by
CGA).

AIUI, in the above 315 MHz is (nominally) exact; no decimal part.

See for example in <URL:http://www.merlyn.demon.co.uk/pas-time.htm#46C>
and thereabouts.

Of course, if the times that are loaded into a date object were loaded
with full accuracy, to 1 ms, then the least digit would be effectively
random, if used only once. But in some systems the time is presumably
obtained from a primeval DOS call, Int21/2C, which returns H, M, S,
centiseconds in byte-sized registers. Reading 32-bit $40:$6C directly
and converting to milliseconds would have been smarter.
Get (I expect it is still there) The Timing FAQ :
358631 Feb 1 1996 ftp://garbo.uwasa.fi/pc/programming/pctim003.zip
pctim003.zip Timing on the PC under MS-DOS, K.Heidenstrom

<FAQENTRY> ?
It would be useful IMHO to have a list of javascript/OS version
combinations, with, for each, the chronological and numerical
resolutions (e.g. IE4/Win98 : 54.9 ms, 10 ms) or a list of resolution
combinations followed by the systems that have them.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 MIME.
Web <URL:http://www.merlyn.demon.co.uk/> - w. FAQish topics, links, acronyms
PAS EXE etc : <URL:http://www.merlyn.demon.co.uk/programs/> - see 00index.htm
Dates - miscdate.htm moredate.htm js-dates.htm pas-time.htm critdate.htm etc.
Jul 23 '05 #29

P: n/a
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon wrote:
Evertjan. wrote:
<snip>
Don't use <!--, //-->, outdated for years.
What's the disadvantage of this notation?


You could have asked Google before posting, we had this many times before.

So, why the "don't" above?

You waste disk space and bandwidth ;-) Seriously, here are two Worst Cases:

You use this in a HTML document and since the content of the `script'
element is CDATA it is passed "as is" to the script engine which will
yield a script error since `<', `!' and `--' are operators (without
proper operand here).


Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.
You use this in an XHTML document and the whole script is disregarded since
a XML parser may (and most, including Gecko's will) remove comments before
building the parse tree (empty `script' element).


Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
....
]]></script>

which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!-- --><![CDATA[
....
// ]]></script>

just not with pre-JS browsers.

<script language="javascript" type="text/javascript"><!-- --><![CDATA[
// ><!--
....
// --><]]></script>

would, I guess, also work in pre-JS browsers that were never
standards-compliant (don't recognise the <![CDATA[ ... ]]> syntax)....

But then again, going this far really is going to be typo-prone.

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #30

P: n/a
Stewart Gordon schrieb:
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon wrote:
Evertjan. wrote:
Don't use <!--, //-->, outdated for years.
What's the disadvantage of this notation?
You could have asked Google before posting, we had this many times
before.
[...]
You use this in a HTML document and since the content of the
`script' element is CDATA it is passed "as is" to the script
engine which will yield a script error since `<', `!' and `--' are
operators (without proper operand here).


Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.


This is plain, utter nonsense.
You use this in an XHTML document and the whole script is
disregarded since a XML parser may (and most, including Gecko's
will) remove comments before building the parse tree (empty
`script' element).


Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
...
]]></script>


This

1. is not a way of commenting out anything, nor is it required.
It merely declares the content of the `script' element as CDATA
which means that tokens like `<' and `&foo;'are no longer parsed
(default is PCDATA -- parsed character data),

2. works with a proper XML parser only, e.g. Gecko. It does
not work with the XML parser of Opera versions (6.12-7.0)
I have tested with. Those UAs silently ignore the script
then (maybe this is fixed by now).

3. language="javascript" is deprecated and as such not part
of XHTML generally but only of XHTML 1.0 Transition which
one does not want to use.
which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!--
--><![CDATA[ ...
// ]]></script>
It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.

It is not compatible with HTML, as there is no specification that
says that a UA MUST or SHOULD support this deprecated method of
commenting out scripts, especially not the HTML 4.01 Specification.
just not with pre-JS browsers.
Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script. In that perspective, and
only in that, this notation is compatible to anything. However,
(kind-of-)HTML 2.0 UAs are obsolete since RFC 2854.
<script language="javascript" type="text/javascript"><!--
--><![CDATA[ // ><!--
...
// --><]]></script>
would, I guess, also work in pre-JS browsers that were never
standards-compliant (don't recognise the <![CDATA[ ... ]]>
syntax)....


No, it won't, for the reasons already presented. Learn how to read.
PointedEars
Jul 23 '05 #31

P: n/a
Stewart Gordon schrieb:
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon wrote:
Evertjan. wrote:
Don't use <!--, //-->, outdated for years.
What's the disadvantage of this notation?
You could have asked Google before posting, we had this many times
before.
[...]
You use this in a HTML document and since the content of the
`script' element is CDATA it is passed "as is" to the script
engine which will yield a script error since `<', `!' and `--' are
operators (without proper operand here).


Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.


This is plain, utter nonsense.
You use this in an XHTML document and the whole script is
disregarded since a XML parser may (and most, including Gecko's
will) remove comments before building the parse tree (empty
`script' element).


Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
...
]]></script>


This

1. is not a way of commenting out anything, nor is it required.
It merely declares the content of the `script' element as CDATA
which means that tokens like `<' and `&foo;'are no longer parsed
(default is PCDATA -- parsed character data),

2. works with a proper XML parser only, e.g. Gecko. It does
not work with the XML parser of Opera versions (6.12-7.0)
I have tested with. Those UAs silently ignore the script
then (maybe this is fixed by now).

3. language="javascript" is deprecated and as such not part
of XHTML generally but only of XHTML 1.0 Transition which
one does not want to use.
which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!--
--><![CDATA[ ...
// ]]></script>
It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.

It is not compatible with HTML, as there is no specification that
says that a UA MUST or SHOULD support this deprecated method of
commenting out scripts, especially not the HTML 4.01 Specification.
just not with pre-JS browsers.
Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script. In that perspective, and
only in that, this notation is compatible to anything. However,
(kind-of-)HTML 2.0 UAs are obsolete since RFC 2854.
<script language="javascript" type="text/javascript"><!--
--><![CDATA[ // ><!--
...
// --><]]></script>
would, I guess, also work in pre-JS browsers that were never
standards-compliant (don't recognise the <![CDATA[ ... ]]>
syntax)....


No, it won't, for the reasons already presented. Learn how to read.
PointedEars
Jul 23 '05 #32

P: n/a
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon schrieb: <snip>
Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.


This is plain, utter nonsense.


Try this code:

----------
document.write('Comment follows '); <!-- document.write('In comment ');
var x = 10;

if (10 <!-- x
) {
document.write('Comment!');
} else {
document.write('No comment');
}
----------

How would you explain the result? It's the same whether in a .js file,
or in a script block with or without an HTML comment around the whole
thing. And it works in both Mozilla and Safari, and in two of these
cases in IE.
You use this in an XHTML document and the whole script is
disregarded since a XML parser may (and most, including Gecko's
will) remove comments before building the parse tree (empty
`script' element).


Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
...
]]></script>


This

1. is not a way of commenting out anything,


I never indicated that it was.
nor is it required.
It merely declares the content of the `script' element as CDATA
which means that tokens like `<' and `&foo;'are no longer parsed
(default is PCDATA -- parsed character data),
I see....
2. works with a proper XML parser only, e.g. Gecko. It does
not work with the XML parser of Opera versions (6.12-7.0)
I have tested with. Those UAs silently ignore the script
then (maybe this is fixed by now).
OK, so there are buggy XML parsers as well.
3. language="javascript" is deprecated and as such not part
of XHTML generally but only of XHTML 1.0 Transition which
one does not want to use.
which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!--
--><![CDATA[ ...
// ]]></script>
It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.


How do you work that out? The comment has nothing inside it (besides
one space), so the XML parser has nothing to lose by removing it.

(FTM, what's happened to the line breaks? I had them either side of
"..." and nowhere else.)
It is not compatible with HTML, as there is no specification that
says that a UA MUST or SHOULD support this deprecated method of
commenting out scripts, especially not the HTML 4.01 Specification.
Do you mean the HTML 4.01 spec gives UAs the choice of parsing the
contents of script blocks as HTML or CDATA? I thought the content of a
script element was strictly CDATA. I'll have to investigate....
just not with pre-JS browsers.


Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script.


That will depend on how the UA treats what it sees as invalid HTML
syntax. I can see that either:

- it will see the whole <![CDATA[ ... ]]> block as one unknown HTML tag
and therefore ignore it
- there is a '>' sign somewhere within the script, causing the content
between it and the closing </script> tag to be written out to the page
- some 'error-correction' rule causes the whole <![CDATA[ ... ]]> block,
delimiters and all, to be written out to the page.
In that perspective, and only in that, this notation is compatible to
anything. However, (kind-of-)HTML 2.0 UAs are obsolete since RFC
2854.
<script language="javascript" type="text/javascript"><!--
--><![CDATA[ // ><!--
...
// --><]]></script>
would, I guess, also work in pre-JS browsers that were never
standards-compliant (don't recognise the <![CDATA[ ... ]]>
syntax)....


No, it won't, for the reasons already presented. Learn how to read.


What has how to read to do with anything?

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #33

P: n/a
Stewart Gordon <sm*******@yahoo.com> writes:
Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.
It's not part of Microsoft's JScript.
<URL:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jslrfjscriptstatementstoc.asp>
Notice the inclusion of // and /* */ comments, but nothing about <!--.

The token "<!--" is also absent from this description of Netscape's
JavaScript 1.3:
<URL:http://docs.sun.com/source/816-6408-10/stmt.htm#1014739>
However, when Javascript is used in a browser, it is traditional that
lines starting with <!-- is ignored.

The tradition is described in "Hiding scripts within comment tags" in
<URL:http://wp.netscape.com/eng/mozilla/3.0/handbook/javascript/getstart.htm#1006443>

So, I disagree that "<!--" is a special token in Javascript, nor is it
isn't part of ECMAScript, the only official *standard* for these
languages. It is a browser tradition that lies beyond the language.

(You could just as well say that <!-- is a token in vbscript, as IE
ignores lines starting with it in script tags of type "text/vbscript"
as well).
Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
...
]]></script>


Yes, you can do that, but it was an argument against adding unneeded
<!--'s: if you ever inadvertedly do it in an XHTML page instead of an
HTML page, your entire script goes away. It might not do anything
in an HTML page, but it's a dangerous, and unnecessary, habit to have.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #34

P: n/a
Stewart Gordon wrote:
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon schrieb:


<snip>
Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.

This is plain, utter nonsense.

Try this code:

----------
document.write('Comment follows '); <!-- document.write('In comment ');
var x = 10;

if (10 <!-- x
) {
document.write('Comment!');
} else {
document.write('No comment');
}
----------

How would you explain the result? It's the same whether in a .js file,
or in a script block with or without an HTML comment around the whole
thing. And it works in both Mozilla and Safari, and in two of these
cases in IE.


Your assertion that "<!-- is a special token in JS" can't be
defended. The only single line comment marker in the ECMAScript
Language Specification is '//'.

It may be that when parsing page content, *browsers* treat '<!--' as
if it were '//', but that is not defined in the specification noted
above. It is likely that browsers behave as suggested because of the
widespread use of '<!--' within script tags in order to hide the
content from browsers that do not understand the script element, but
that does not prove anything in regard to how it might be treated by
a JavaScript interpreter.

[...]

--
Rob
Jul 23 '05 #35

P: n/a
Lasse Reichstein Nielsen wrote:
Stewart Gordon <sm*******@yahoo.com> writes:
Actually, <!-- is a special token in JS. It's a single-line comment
notation, just like //.


It's not part of Microsoft's JScript.
<URL:http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jslrfjscriptstatementstoc.asp>
Notice the inclusion of // and /* */ comments, but nothing about <!--.

<snip>

Correction: it's an undocumented part of Microsoft's JScript. See the
cousin of this post.

And calling comments statements is kind of pushing definitions....

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #36

P: n/a
Stewart Gordon <sm*******@yahoo.com> writes:
Lasse Reichstein Nielsen wrote:
Stewart Gordon <sm*******@yahoo.com> writes:
Actually, <!-- is a special token in JS. It's a single-line comment
.... It's not part of Microsoft's JScript.
.... Correction: it's an undocumented part of Microsoft's JScript. See the
cousin of this post.


No, it isn't.
If you make a file called "test.js" containing:
---
var x = 42;
<!-- comment
WScript.Echo(x);
---
and run it from the command line as "wscript test.js", then you get
a syntax error on line 2. Change "<!--" to "//" and you get the result 42.

This *is* Microsoft JScript, running as part of the Windows Scripting
Host.

It *is* an undocumented part of Internet Explorer, not JScript itself.

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #37

P: n/a
In article <MB******************@twister.nyroc.rr.com>, Mick White
<mw***********@rochester.rr.com> writes
Richard Cornford wrote:
Mick White wrote:
John G Harris wrote: <snip>
My system's Date objects supply about 19 different values per
second, so the millisecond values are unlikely to be random
enough to be useful.


<snip>
At the risk of beating a dead horse,I'd day it's random enough for a
one-off.
Mick


It depends on the circumstances, doesn't it?

First, the user can use the Refresh button to get another safety tip. Or
flick to another page and back; with broadband this can be pretty quick.
The Date values will be highly correlated and not very random.

Second, some millisecond values might never appear, or appear much less
often than others. It would be unfortunate if the most important safety
tip was never displayed.

Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.

John
--
John Harris
Jul 23 '05 #38

P: n/a
John G Harris wrote:
In article <MB******************@twister.nyroc.rr.com>, Mick White
<mw***********@rochester.rr.com> writes
Richard Cornford wrote:
Mick White wrote:
John G Harris wrote:

<snip>

>My system's Date objects supply about 19 different values per
>second, so the millisecond values are unlikely to be random
>enough to be useful.


<snip>
At the risk of beating a dead horse,I'd day it's random enough for a
one-off.
Mick

It depends on the circumstances, doesn't it?

First, the user can use the Refresh button to get another safety tip. Or
flick to another page and back; with broadband this can be pretty quick.
The Date values will be highly correlated and not very random.


Not really, but:
(Math.round(new Date()/10))%10
as JS suggests would eliminate this.

Second, some millisecond values might never appear, or appear much less
often than others. It would be unfortunate if the most important safety
tip was never displayed. Did you look at my sample page?
http://home.rochester.rr.com/mickweb...pt/random.html

Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.
You've got me there...
John

Jul 23 '05 #39

P: n/a
JRS: In article <q1**************@jgharris.demon.co.uk>, dated Fri, 8
Apr 2005 15:37:30, seen in news:comp.lang.javascript, John G Harris
<jo**@nospam.demon.co.uk> posted :
First, the user can use the Refresh button to get another safety tip. Or
flick to another page and back; with broadband this can be pretty quick.
The Date values will be highly correlated and not very random.
But there will, if anything, be an increased chance of not getting the
same choice on two consecutive occasions, which is good.
Second, some millisecond values might never appear, or appear much less
often than others. It would be unfortunate if the most important safety
tip was never displayed.
It is quite common for only integer centiseconds to be used. But I
recall no system that does not show all possible centisecond values over
the course of a moderate number of seconds.
Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.


Since it is fairly likely that, in at least some browsers, the seed of
Math.random is initialised from the time of day, there is at least a
possibility that the same effect will occur when using that.
If the seed of a random generator is initialised by the system time-of-
day, one can for most purposes protect by immediately calling Random for
a number of times dependent on the date.
Math.floor(new Date()/864e5) - 12881
should do; it gives zero today, one tomorrow, etc., if used in Iceland.
I recall that the IT staff of a newer UK university, some while ago, had
a business game programmed to be run each day of a one-week course (the
regular users were told of this, since it would affect normal customer
service). Everyone, of course, knows that such programs use randomised
decisions. I pointed out to the staff that if the program was started
at exactly the same time each day (which was what site management had
decreed : 0900, IIRC), then there was an increased risk of getting the
same "random" decisions each day, which the players might notice. There
was an immediate burst of action among the programming and operations
staff, to make sure that, whatever might go wrong, it wouldn't be that!

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #40

P: n/a
Mick White wrote:
John G Harris wrote:

[...]

Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.

You've got me there...


To think that the Windows Task Scheduler could guarantee loading a
page within 10 or even 100 milliseconds of a specified time, every
time, is to presume to much.

PS. Just wanted to be part of the longest thread in quite some time.

--
Rob
Jul 23 '05 #41

P: n/a
Mick White wrote:
John G Harris wrote:
Mick White wrote: <snip> It depends on the circumstances, doesn't it?

First, the user can use the Refresh button to get another
safety tip. Or flick to another page and back; with
broadband this can be pretty quick. The Date values will
be highly correlated and not very random.


Not really, but:
(Math.round(new Date()/10))%10
as JS suggests would eliminate this.

<snip>

Rather than going round and round in a discussion of whether, where and
with what manipulation, the output of a Date object might be considered
suitably random wouldn't some sort of statement of a (any) reason for
using a Date object in place of Math.random() be a good idea? Because
without an objectively verified problem with Math.random() being
identified alternatives may be superfluous.

Richard.
Jul 23 '05 #42

P: n/a
In article <y3**************@merlyn.demon.co.uk>, Dr John Stockton
<sp**@merlyn.demon.co.uk> writes
JRS: In article <q1**************@jgharris.demon.co.uk>, dated Fri, 8
Apr 2005 15:37:30, seen in news:comp.lang.javascript, John G Harris
<jo**@nospam.demon.co.uk> posted :


<snip>
Second, some millisecond values might never appear, or appear much less
often than others. It would be unfortunate if the most important safety
tip was never displayed.


It is quite common for only integer centiseconds to be used. But I
recall no system that does not show all possible centisecond values over
the course of a moderate number of seconds.


Unfortunately we're talking about all versions of all browsers on all
hardware that runs browsers. Even if you restrict yourself to the
world's only patriotic browser there could be a security update next
week that changes its behaviour.

Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.


Since it is fairly likely that, in at least some browsers, the seed of
Math.random is initialised from the time of day, there is at least a
possibility that the same effect will occur when using that.

<snip>

I thought of that, but a numerate programmer (*) would avoid that
problem.

John

* So there's a problem.
--
John Harris
Jul 23 '05 #43

P: n/a
In article
<42***********************@per-qv1-newsreader-01.iinet.net.au>, RobG
<rg***@iinet.net.auau> writes
Mick White wrote:
John G Harris wrote:
[...]

Third, some maniac user might arrange for visits to the site to be
started by the Windows Task Scheduler, at the same time every day.

You've got me there...


To think that the Windows Task Scheduler could guarantee loading a
page within 10 or even 100 milliseconds of a specified time, every
time, is to presume to much.


Yeah, but sometimes could be too often.
PS. Just wanted to be part of the longest thread in quite some time.


You're welcome!

John
--
John Harris
Jul 23 '05 #44

P: n/a
JRS: In article <d3*******************@news.demon.co.uk>, dated Sat, 9
Apr 2005 15:17:37, seen in news:comp.lang.javascript, Richard Cornford
<Ri*****@litotes.demon.co.uk> posted :
Rather than going round and round in a discussion of whether, where and
with what manipulation, the output of a Date object might be considered
suitably random wouldn't some sort of statement of a (any) reason for
using a Date object in place of Math.random() be a good idea? Because
without an objectively verified problem with Math.random() being
identified alternatives may be superfluous.


Very simple.

Using Math.random as in FAQ 4.22 (with the possible addition of %1 for
Opera) just works; there is no benefit to be obtained from discussing
possible peculiarities of its use, except for cryptographers and those
with a good understanding of mathematics and statistics.

But using (in News) a Date Object for random number generation leads to
an interesting discussion on the behaviours of new Date() in various
operating systems, disclosing under-realised features of its behaviour
that can be worth knowing in other contexts.
And, on my system, new Date() is about 20 times better than
Math.random() is at consuming CPU time and so creating the illusion of
thoughtfulness in a routine.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #45

P: n/a
Stewart Gordon schrieb:
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon schrieb:
You use this in an XHTML document and the whole script is
disregarded since a XML parser may (and most, including Gecko's
will) remove comments before building the parse tree (empty
`script' element).

Actually, the XHTML way is different again. Something like

<script language="javascript" type="text/javascript"><![CDATA[
...
]]></script>
This

1. is not a way of commenting out anything,


I never indicated that it was.


What was "the XHTML way" in a subthread dealing with whether
or not to comment out scripts content supposed to mean?
3. language="javascript" is deprecated and as such not part
of XHTML generally but only of XHTML 1.0 Transition which
one does not want to use.
which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!--
--><![CDATA[ ...
// ]]></script>


It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.


How do you work that out? The comment has nothing inside it (besides
one space), so the XML parser has nothing to lose by removing it.


You're right, my bad. On the other hand, an XML parser knows the
`script' element, so no comment is necessary.
(FTM, what's happened to the line breaks? I had them either side of
"..." and nowhere else.)


Shit happens. But fortunately it does not make a difference here.
It is not compatible with HTML, as there is no specification that
says that a UA MUST or SHOULD support this deprecated method of
commenting out scripts, especially not the HTML 4.01 Specification.


Do you mean the HTML 4.01 spec gives UAs the choice of parsing the
contents of script blocks as HTML or CDATA? I thought the content
of a script element was strictly CDATA. I'll have to investigate....


That is the contradiction that is created by suggesting in the
HTML 4.01 Specitication that scripts can be commented out. If
the content is PCDATA, the markup parser is responsible for
recognizing it; if it is CDATA, the script engine is responsible.
*Any* script engine for HTML UAs would have to support it then.
However, HTML 4.01 does not specify script engine behavior.
just not with pre-JS browsers.


Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script.


That will depend on how the UA treats what it sees as invalid HTML
syntax. [...]


Agreed. But do you really want to support a UA that is this borken?
In that perspective, and only in that, this notation is compatible
to anything. However, (kind-of-)HTML 2.0 UAs are obsolete since
RFC 2854.
<script language="javascript" type="text/javascript"><!--
--><![CDATA[ // ><!--
...
// --><]]></script>
would, I guess, also work in pre-JS browsers that were never
standards-compliant (don't recognise the <![CDATA[ ... ]]>
syntax)....


No, it won't, for the reasons already presented. Learn how to
read.


What has how to read to do with anything?


You put solutions into the discussion which had already been
discarded for valid reasons.
PointedEars
Jul 23 '05 #46

P: n/a
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon schrieb:
Thomas 'PointedEars' Lahn wrote: <snip>
1. is not a way of commenting out anything,
I never indicated that it was.


What was "the XHTML way" in a subthread dealing with whether
or not to comment out scripts content supposed to mean?


I meant the XHTML way of enclosing script code. Sorry for the confusion.
3. language="javascript" is deprecated and as such not part
of XHTML generally but only of XHTML 1.0 Transition which
one does not want to use.

which of course will screw up in pre-XHTML browsers. OTOH this is
compatible with both HTML and XHTML:

<script language="javascript" type="text/javascript"><!--
--><![CDATA[ ...
// ]]></script>

It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.


How do you work that out? The comment has nothing inside it (besides
one space), so the XML parser has nothing to lose by removing it.


You're right, my bad. On the other hand, an XML parser knows the
`script' element, so no comment is necessary.


You miss the point. I was trying to come up with something that's
simultaneously compatible with HTML and XHTML.

<snip> That is the contradiction that is created by suggesting in the
HTML 4.01 Specitication that scripts can be commented out. If
the content is PCDATA, the markup parser is responsible for
recognizing it; if it is CDATA, the script engine is responsible.
*Any* script engine for HTML UAs would have to support it then.
However, HTML 4.01 does not specify script engine behavior.


Indeed. ECMAScript does that.

It was certainly at least implied to me that at least one version of the
ECMAScript spec has the <!-- comment in it. But I can't seem to find it
at the moment.

And FWIW, I also tried adapting the earlier piece of code to run under
DMDScript, a console-based ECMAScript interpreter. And again, I got the
behaviour indicating that <!-- signifies a comment.
just not with pre-JS browsers.

Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script.


That will depend on how the UA treats what it sees as invalid HTML
syntax. [...]

Agreed. But do you really want to support a UA that is this borken?


Believe me, thousands do. I guess because so many people use them, and
so it gets into a vicious circle.

<snip>
No, it won't, for the reasons already presented. Learn how to
read.


What has how to read to do with anything?


You put solutions into the discussion which had already been
discarded for valid reasons.


No I didn't. I put solutions into the discussion which you subsequently
"discarded". Learn how to determine the time-sequence of events.

Stewart.

--
My e-mail is valid but not my primary mailbox. Please keep replies on
the 'group where everyone may benefit.
Jul 23 '05 #47

P: n/a
Stewart Gordon wrote:
Thomas 'PointedEars' Lahn wrote:
Stewart Gordon schrieb:
Thomas 'PointedEars' Lahn wrote:
> [...] OTOH this is compatible with both HTML and XHTML:
>
> <script language="javascript" type="text/javascript"><!--
> --><![CDATA[ ...
> // ]]></script>
It is not compatible with XHTML, as an XML parser is allowed to
remove the comment (and for the reasons above) as I already wrote.
How do you work that out? The comment has nothing inside it (besides
one space), so the XML parser has nothing to lose by removing it. You're right, my bad. On the other hand, an XML parser knows the
`script' element, so no comment is necessary.


You miss the point. I was trying to come up with something that's
simultaneously compatible with HTML and XHTML.


But it isn't. `<![CDATA[ ... ]]>' is not supposed to work in HTML,
it is an XML declaration:

<http://www.w3.org/TR/xml11/#sec-cdata-sect>

XML is based on SGML, and HTML is based on SGML. But HTML is _not_
based on XML, *XHTML* is.
<snip>
That is the contradiction that is created by suggesting in the
HTML 4.01 Specitication that scripts can be commented out. If
the content is PCDATA, the markup parser is responsible for
recognizing it; if it is CDATA, the script engine is responsible.
*Any* script engine for HTML UAs would have to support it then.
However, HTML 4.01 does not specify script engine behavior.
Indeed. ECMAScript does that.

It was certainly at least implied to me that at least one version of the
ECMAScript spec has the <!-- comment in it. But I can't seem to find it
at the moment.


There is none. Trust me.
And FWIW, I also tried adapting the earlier piece of code to run under
DMDScript, a console-based ECMAScript interpreter. And again, I got the
behaviour indicating that <!-- signifies a comment.


Well, we have already seen examples parsed by the original JavaScript and
JScript engines that don't work this way. So this trick does not qualify
as solution.
> just not with pre-JS browsers.
Nonsense. *Pre*-JS browsers would be (kind-of-)HTML 2.0 browsers.
Since the `script' element was not defined prior to HTML 3.2, those
UAs will do silently ignore the script.
That will depend on how the UA treats what it sees as invalid HTML
syntax. [...]

Agreed. But do you really want to support a UA that is this borken?


Believe me, thousands do. I guess because so many people use them, and
so it gets into a vicious circle.


As to my experience, most people who subscribed to this group understand
that and why this method has become obsolete nonsense, and stop using it.
You put solutions into the discussion which had already been
discarded for valid reasons.


No I didn't. I put solutions into the discussion which you subsequently
"discarded". Learn how to determine the time-sequence of events.


They have had been already discarded by previous posters, BTW not only
in *this* thread.
PointedEars
Jul 23 '05 #48

P: n/a
Thomas 'PointedEars' Lahn wrote:
XML is based on SGML, and HTML is based on SGML. But HTML is _not_
based on XML, *XHTML* is.


You are opening a door for misunderstanding by using "based on"
ambivalently.

XML is based on SGML.

HTML is an instance of SGML.

XHTML is based on HTML, and is an instance of XML.

--
John W. Kennedy
"Sweet, was Christ crucified to create this chat?"
-- Charles Williams. "Judgement at Chelmsford"
Jul 23 '05 #49

P: n/a
John W. Kennedy wrote:
Thomas 'PointedEars' Lahn wrote:
XML is based on SGML, and HTML is based on SGML. But HTML is _not_
based on XML, *XHTML* is.
You are opening a door for misunderstanding by using "based on"
ambivalently.


Fair enough.
XML is based on SGML.

HTML is an instance of SGML.

XHTML is based on HTML, and is an instance of XML.


Actually, HTML is an SGML application and XHTML, based on HTML, is an XML
application which is an SGML application. Enough nitpicking for now?

What is important here but was snipped by you is that CDATA Sections are
only defined in XML and so are valid only in XML applications, not in HTML.
PointedEars
--
Microsoft has been doing a really bad job on their OS. -- Linus Torvalds
Jul 23 '05 #50

62 Replies

This discussion thread is closed

Replies have been disabled for this discussion.