JavaScript random number Generation method

Source: Internet
Author: User
Tags shuffle

Implementing random numbers is a common programming task in a variety of programming languages, and here's how to implement random numbers in JavaScript. The first method is implemented by overriding the Math.random method, and the second method is changed from a C implementation, which can realize the programming purpose. Tongyu County Zhong agrochemical

Directly on the code:

01 <script language="javascript">   
02 varnative_random = Math.random;
03 Math.random = function(min, max, exact) {
04     if(arguments.length === 0)
05     {
06         returnnative_random();
07     }
08     elseif(arguments.length === 1)
09     {
10         max = min;
11         min = 0;
12     }
13     varrange = min + (native_random()*(max - min));
14     returnexact === void(0) ? Math.round(range) : range.toFixed(exact);
15 };
16 document.write(Math.random());
17 document.write(‘<br />‘);
18 document.write(Math.random(10));
19 document.write(‘<br />‘);
20 document.write(Math.random(3,10));
21 document.write(‘<br />‘);
22 document.write(Math.random(2,10,4));
23 </script>

The results of the program run as follows:

1 0.2989420900121331
2 7
3 9
4 2.2469

How do I implement random numbers without using math.random? The following function is changed from a C implementation:

01 varrandom = (function(){
02     varhigh = 1, low = 1 ^ 0x49616E42;
03     varshuffle = function(seed){
04         high = seed;
05         low = seed ^ 0x49616E42;
06     }
07     
08     returnfunction(){
09         vara = newDate()-0
10         shuffle(a);
11         high = (high << 16) + (high >> 16);
12         high += low;
13         low += high;
14         returnhigh;
15     }
16 })();
17  
18 p(random());

JavaScript random number Generation method

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.