LEARNING JAVASCRIPT - Trang 258

Function

Description

Examples

Math.trunc(x)

The integral part of x (all
fractional digits removed)

Math

.

trunc

(

7.7

)

// 7

Math

.

trunc

(

-

5.8

)

// -5

Math.round(x)

x rounded to the nearest
integer

Math

.

round

(

7.2

)

// 7

Math

.

round

(

7.7

)

// 8

Math

.

round

(

-

7.7

)

// -8

Math

.

round

(

-

7.2

)

// -7

Math.min(x1, x2,...)

Returns the minimum
argument

Math

.

min

(

1

,

2

)

// 1

Math

.

min

(

3

,

0.5

,

0.66

)

// 0.5

Math

.

min

(

3

,

0.5

,

-

0.66

)

// -0.66

Math.max(x1, x2,...)

Returns the maximum
argument

Math

.

max

(

1

,

2

)

// 2

Math

.

max

(

3

,

0.5

,

0.66

)

// 3

Math

.

max

(

-

3

,

0.5

,

-

0.66

)

// 0.5

Pseudorandom Number Generation

Pseudorandom number generation is provided by

Math.random

, which returns a

pseudorandom number greater than or equal to 0 and less than 1. You may recall

from algebra that number ranges are often denoted with square brackets (inclusive)

and parentheses (exclusive). In this notation,

Math.random

returns numbers in the

range [0, 1).

Math.random

does not provide any convenience methods for providing pseudoran‐

dom numbers in different ranges.

Table 16-4

shows some general formulas for getting

other ranges. In this table,

x

and

y

denote real numbers and

m

and

n

denote integers.

Table 16-4. Number pseudorandom number generation

Range

Example

[0, 1)

Math.random()

[x, y)

x + (y-x)*Math.random()

Integer in [m, n)

m + Math.floor((n-m)*Math.random())

Integer in [m, n]

m + Math.floor((n-m+1)*Math.random())

A common complaint about JavaScript’s pseudorandom number generator is that it

can’t be seeded, which is important to testing some algorithms involving pseudoran‐

dom numbers. If you need seeded pseudorandom numbers, see David Bau’s

seedran‐

dom.js package

.

234 | Chapter 16: Math

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.