Gaussian Samples With NormFloat64
Draw normal-distributed samples from math/rand/v2 with NormFloat64, scaling the unit variance output to a target mean and standard deviation.
Code
package main
import (
"fmt"
"math"
"math/rand/v2"
)
func main() {
// 固定种子:每次运行的样本序列完全一致
rng := rand.New(rand.NewPCG(42, 7))
// NormFloat64 产出均值 0、方差 1 的正态样本;线性变换到 N(100, 15)
const mean, stddev = 100.0, 15.0
samples := make([]float64, 8)
for i := range samples {
samples[i] = mean + stddev*rng.NormFloat64()
}
for _, s := range samples {
fmt.Printf("sample: %.2f\n", s)
}
// 复核经验均值与标准差落在期望附近
var total, sq float64
for _, s := range samples {
total += s
}
empiricalMean := total / float64(len(samples))
for _, s := range samples {
d := s - empiricalMean
sq += d * d
}
fmt.Printf("empirical mean %.2f (target %.0f)\n", empiricalMean, mean)
fmt.Printf("empirical stddev %.2f (target %.0f)\n", math.Sqrt(sq/float64(len(samples))), stddev)
}How the snippet works
Everything that executes sits inside the function main.
A single loop drives the file — for i := range samples.
Caveats
- The standard library is the whole story here — nothing to install at all.
Applying it
The main signature is written as func main()
The run emits 3 labeled sections — sample:, empirical mean, empirical stddev — one per step.
Statements that matter most here
for _, s := range samples {
fmt.Printf("sample: %.2f\n", s)
}
for _, s := range samples {
total += s
}
for _, s := range samples {
d := s - empiricalMean
sq += d * d
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.GCD & LCM CalculatorFind the greatest common divisor and least common multiple of two or more integers, computed exactly with BigInt.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
FAQ
- What does Gaussian Samples With NormFloat64 print when run?
- Invoke the file as-is — the `sample:`, `empirical mean`, `empirical stddev` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.