Available CategoriesAdobeMacromediaProgrammingSQLServer AdministrationNetworkingMicrosoft ProductsMac OSLinux systemsMobile devicesXMLCertificationMiscAvailable Tutorials.NET Framework Essentials.NET Programming securityC# In A Nutshell TutorialProgramming C.SharpMastering Visual Studio .NETASP.NETWeb Solutions based on ASP.NET and ADO.NETJava data objectsJava extreme programmingJava performance tuningJava development on pda's. Building applications for pocket pc and palm devicesJavaScript and DHTMLLearning UMLUMLLearning XMLCocoaProgramming CppPerl objects, references and modulesPerl tutorialPython tutorialPython. Text processingPocket pc network programmingPHP & MySQL. Building web database applicationsPHP & MySQL. Programming for beginnersPHP, MySQL and Apache in 24 hoursSoftware architecture in practiceSoftware engineering and computer gamesBuilding Solutions With the Microsoft .NET Compact FrameworkProgramming Microsoft Visual C# 2005ActionscriptMastering Delphi 7Ado.netPractical mod_perlPerl for bioinformaticsWeb ServicesPrinciples of Secure CodingC/C++ Secure ProgrammingASP.NET AJAXVisual C#Borland C++ Builder 6 Developer's Guide |
2.7 Generating Pseudorandom Numbers
2.7.1 ProblemYou want to generate a random number. 2.7.2 SolutionThe Math.random( ) method returns a pseudorandom number between 0 and 1. To calculate a pseudorandom integer value within a range starting with zero, use the formula: var result = Math.floor(Math.random( ) * (n + 1); where n is the highest acceptable integer of the range. To calculate a pseudorandom integer number within a range starting at a number other than zero, use the formula: var result = Math.floor(Math.random( ) * (n - m + 1)) + m; where m is the lowest acceptable integer of the range, and n is the highest acceptable integer of the range. 2.7.3 DiscussionThe previous examples focus on random integers, such as the kind you might use for values of a game cube (a die with numbers from 1 through 6). But you can remove the Math.floor( ) call to let the rest of the expression create random numbers with decimal fractions if you need them. JavaScript's random number generator does not provide a mechanism for adjusting the seed to assure more genuine randomness. Thus, at best you can treat it as a pseudorandom number generator. 2.7.4 See AlsoSection 2.0.2 in the introduction of this chapter.
|