How to Get Float32 Type Random Number in Golang?


Generating random numbers is a common task in many programming applications. In Go, we can use the math/rand package to generate random numbers. In this article, we will explore how to get a random number of type float32 in Go.

Using The Rand Package

The math/rand package in Go provides a simple way to generate random numbers. We can use the Float32() function to generate a random number of type float32.

Example

Here's an example −

package main

import (
   "fmt"
   "math/rand"
   "time"
)

func main() {
   rand.Seed(time.Now().UnixNano())
   num := rand.Float32()
   fmt.Println("Random number:", num)
}

In this code, we use the rand.Seed() function to seed the random number generator with the current time. Then, we use the rand.Float32() function to generate a random number of type float32, and we print it to the console.

Output

Random number: 0.2767483

Generating a Range of Random Float32 Numbers

We can also generate a range of random numbers of type float32 using the rand.Float32() function. We can specify a range by subtracting the minimum value from the maximum value and multiplying it by the random number generated. Then, we add the minimum value to get a random number in the desired range.

Example

Here's an example −

package main

import (
   "fmt"
   "math/rand"
   "time"
)

func main() {
   rand.Seed(time.Now().UnixNano())
   min := float32(1.0)
   max := float32(10.0)
   num := rand.Float32() * (max - min) + min
   fmt.Println("Random number between", min, "and", max, ":", num)
}

In this code, we use the rand.Seed() function to seed the random number generator with the current time. Then, we define a minimum value and a maximum value for the range of random numbers. We use the formula rand.Float32() * (max - min) + min to generate a random number between the minimum and maximum values, and we print it to the console.

Output

Random number between 1 and 10 : 7.9311614

Conclusion

Generating random numbers of type float32 in Go is simple and straightforward using the math/rand package. We can use the rand.Float32() function to generate a random number of type float32, and we can use the formula rand.Float32() * (max - min) + min to generate a range of random numbers between a minimum and maximum value.

Updated on: 05-May-2023

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements