Generare numeri casuali con le caratteristiche desiderate…
Genera un numero casuale Valori: [ 0.0, 1.0 [ |
Math.random(); |
||
Genera un bit casuale Valori: {0, 1} |
Math.floor(2*Math.random()); |
||
Genera un numero casuale Valori: {minimo, …, massimo} |
Minimo Massimo |
Math.floor((M-m+1)*Math.random()+m); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
<script>function f_random() { var x=document.getElementById("out_rand"); x.value=Math.random(); } function f_bit() { var x=document.getElementById("out_bit") x.value=Math.floor(2*Math.random()); } function f_genera() { var x=document.getElementById("minimo").value; var y=document.getElementById("massimo").value; var m=parseInt(x); var M=parseInt(y); var r=Math.floor((M-m+1)*Math.random()+m); var z=document.getElementById("inter"); z.value=r; } </script> <table bgcolor="#FF9966"> <tbody> <tr> <td>Genera un numero casuale<br/>Valori: [ 0.0, 1.0 [</td> <td><input id="out_rand" readonly="readonly" size="25" type="text" /></td> <td><input type="button" value="Math.random()" onClick="f_random()"/></td> <td><code>Math.random();</code></td> </tr> <tr> <td>Genera un bit casuale<br/>Valori: {0, 1}</td> <td><input id="out_bit" readonly="readonly" size="4" type="text" /></td> <td><input type="button" value="Un bit" onClick="f_bit()" /></td> <td><code>Math.floor(2*Math.random());</code></td> </tr> <tr> <td>Genera un numero casuale<br/>Valori: {minimo, ..., massimo}</td> <td><input id="minimo" size="4" type="text" value="1" /> Minimo<br/> <input id="massimo" size="4" type="text" value="10" /> Massimo<br/> <input id="inter" readonly="readonly" size="4" type="text" /></td> <td><input type="button" value="Genera!" onClick="f_genera()" /></td> <td><code>Math.floor((M-m+1)*Math.random()+m);</code></td> </tr> </tbody> </table> |