Home Backend Development Golang How to generate non-repeating random numbers in golang

How to generate non-repeating random numbers in golang

Dec 23, 2019 am 10:46 AM
random number

How to generate non-repeating random numbers in golang

Go's math/rand package provides an API for generating random numbers. The important APIs are as follows:

// 该函数设置随机种子
// 若不调用此函数设置随机种子,则默认的种子值为1,由于随机算法是固定的,
// 如果每次都以1作为随机种子开始产生随机数,则结果都是一样的,因此一般
// 都需要调用此函数来设置随机种子,通常的做法是以当前时间作为随机种子
// 以保证每次随机种子都不同,从而产生的随机数也不通
// 该函数协程安全
func Seed(seed int64)

// 以下函数用来生成相应数据类型的随机数,带n的版本则生成[0,n)的随机数。
// 注意生成的随机数都是非负数
func Float32() float32
func Float64() float64
func Int() int
func Int31() int32  // 注意该函数只返回int32表示范围内的非负数,位数为31,因此该函数叫做Int31
func Int31n(n int32) int32
func Int63() int64
func Int63n(n int64) int64
func Intn(n int) int
func Uint32() uint32
func Uint64() uint64

// 另外,rand包还提供了一个类,接口和上面的大致相同:
type Rand struct {
    // ...
}

// 创建一个以seed为种子的源,注意该源不是协程安全的
func NewSource(seed int64) Source
// 以src为源创建随机对象
func New(src Source) *Rand
// 设置或重置种子,注意该函数不是协程安全的
func (r *Rand) Seed(seed int64)
// 下面的函数和全局版本的函数功能一样
func (r *Rand) Float32() float32
func (r *Rand) Float64() float64
func (r *Rand) Int() int
func (r *Rand) Int31() int32
func (r *Rand) Int31n(n int32) int32
func (r *Rand) Int63() int64
func (r *Rand) Int63n(n int64) int64
func (r *Rand) Intn(n int) int
func (r *Rand) Uint32() uint32
func (r *Rand) Uint64() uint64
Copy after login

When generating random numbers, it is best to use the current time as the random seed. A good choice, you can use the time package to generate the current time:

// 返回当前时间
func Now() Time

// 为了将Time类型转换为int64类型以作为随机种子
// 可以使用如下两个函数:

// 返回从1970年1月1日到t的秒数
func (t Time) Unix() int64
// 返回从1970年1月1日到t的纳秒数
func (t Time) UnixNano() int64
Copy after login

For example

package main
import (
    "fmt"
    "math/rand"
    "time"
)
func main() {
    //
    // 全局函数
    //
    rand.Seed(time.Now().Unix())

    fmt.Println(rand.Int())       // int随机值,返回值为int
    fmt.Println(rand.Intn(100))   // [0,100)的随机值,返回值为int
    fmt.Println(rand.Int31())     // 31位int随机值,返回值为int32
    fmt.Println(rand.Int31n(100)) // [0,100)的随机值,返回值为int32
    fmt.Println(rand.Float32())   // 32位float随机值,返回值为float32
    fmt.Println(rand.Float64())   // 64位float随机值,返回值为float64

    // 如果要产生负数到正数的随机值,只需要将生成的随机数减去相应数值即可
    fmt.Println(rand.Intn(100) - 50) // [-50, 50)的随机值

    //
    // Rand对象
    //
    r := rand.New(rand.NewSource(time.Now().Unix()))

    fmt.Println(r.Int())       // int随机值,返回值为int
    fmt.Println(r.Intn(100))   // [0,100)的随机值,返回值为int
    fmt.Println(r.Int31())     // 31位int随机值,返回值为int32
    fmt.Println(r.Int31n(100)) // [0,100)的随机值,返回值为int32
    fmt.Println(r.Float32())   // 32位float随机值,返回值为float32
    fmt.Println(r.Float64())   // 64位float随机值,返回值为float64

    // 如果要产生负数到正数的随机值,只需要将生成的随机数减去相应数值即可
    fmt.Println(r.Intn(100) - 50) // [-50, 50)的随机值
}
Copy after login

The above is the detailed content of How to generate non-repeating random numbers in golang. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to create a random number generator in Excel How to create a random number generator in Excel Apr 14, 2023 am 09:46 AM

How to use RANDBETWEEN to generate random numbers in Excel If you want to generate random numbers within a specific range, the RANDBETWEEN function is a quick and easy way to do it. This allows you to generate random integers between any two values ​​of your choice. Generate random numbers in Excel using RANDBETWEEN: Click the cell where you want the first random number to appear. Type =RANDBETWEEN(1,500) replacing "1" with the lowest random number you want to generate and "500" with

Java random number generation performance optimization method Java random number generation performance optimization method Jun 30, 2023 pm 12:25 PM

How to optimize random number generation performance in Java development Random numbers are widely used in computer science, especially in cryptography, simulation, games and other fields. In Java development, we often need to generate random numbers to meet various needs. However, the performance of random number generation is often one of the concerns of developers. This article will explore how to optimize random number generation performance in Java development. ThreadLocalRandom class was introduced in Java7 using ThreadLocalRandom class

How to generate random numbers and verification codes using PHP arrays How to generate random numbers and verification codes using PHP arrays Jul 16, 2023 am 08:31 AM

How to use PHP arrays to generate random numbers and verification codes Random numbers and verification codes are very common during the development of websites and applications. PHP provides various methods to generate random numbers and verification codes. This article will introduce how to use PHP arrays to generate random numbers and verification codes, with corresponding code examples. 1. Generate random numbers In PHP, we can use the rand() function to generate random numbers. The rand() function requires two parameters, the minimum value and the maximum value. The sample code is as follows: $min=1;$max=

Generate random numbers using the crypto/rand.Read function from the Go language documentation Generate random numbers using the crypto/rand.Read function from the Go language documentation Nov 04, 2023 pm 03:39 PM

Generate random numbers using Go language Go language is a modern, concise and efficient programming language that provides many built-in libraries for generating random numbers. Among them, the crypto/rand package provides a series of functions to generate secure random numbers. In this article, we will generate random numbers by using the Read function from the crypto/rand package. First, we need to import the crypto/rand package and create a byte array to store the random numbers. The code example is as follows: packagemain

In-depth understanding of random number generation methods and applications in numpy In-depth understanding of random number generation methods and applications in numpy Jan 03, 2024 am 08:23 AM

Explore the method and application of NumPy to generate random numbers. Introduction: Random numbers are widely used in computer science and statistics, such as simulation experiments, data generation and feature selection. In Python, the NumPy (NumericalPython) library is a powerful numerical computing library that provides many functions for generating random numbers. This article will explore the random number generation method in NumPy and give specific code examples. 1. NumPy’s random number generation function provided by NumPy

How to use Random.nextInt() method to generate random numbers in Java? How to use Random.nextInt() method to generate random numbers in Java? Nov 18, 2023 pm 03:44 PM

How to use Random.nextInt() method to generate random numbers in Java? Random numbers are widely used in computer science and can be used to generate passwords, random events in games, random sampling in data science, etc. Java provides the Random class to generate random numbers, and the nextInt() method can be used to generate a random integer. Below I will introduce how to use the Random.nextInt() method to generate random numbers and provide specific code examples. First, we need

How to avoid generating duplicate random numbers in Golang? How to avoid generating duplicate random numbers in Golang? Jun 01, 2024 pm 04:46 PM

How to avoid generating duplicate random numbers in Golang: Create a new random number generator rand.New(rand.Source). Use rand.NewSource(time.Now().UnixNano()) as the entropy source. Use rand.Intn(n) to generate random integers.

Generate random numbers using Java's Math.random() function Generate random numbers using Java's Math.random() function Jul 24, 2023 am 08:45 AM

Using Java's Math.random() function to generate random numbers. Random numbers are a very common concept in computer programming and can help us implement various functions, such as generating random passwords, lottery draws, random events in games, etc. In Java, we can use Math.random() function to generate random numbers. The Math.random() function is a static method in the Java standard library. It returns a random double type number greater than or equal to 0 and less than 1. pass

See all articles