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.

GoConfig Management

Code

gosnippet
35 lines
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

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.