go: add slices manually

This commit is contained in:
NunoSempere 2024-02-16 14:40:54 +01:00
parent 14e298c3c9
commit 06438c522d
2 changed files with 33 additions and 4 deletions

View File

@ -2,6 +2,7 @@
- [x] Look into randomness sources in go - [x] Look into randomness sources in go
- rand/v2 api: <https://pkg.go.dev/math/rand/v2> - rand/v2 api: <https://pkg.go.dev/math/rand/v2>
- [x] Test with a million samples of a simple lognormal, just to get a sense of speed - [x] Test with a million samples of a simple lognormal, just to get a sense of speed
- [ ] Add mixture distribution - [x] Add mixture distribution
- [x] Anonymous functions for nested: https://stackoverflow.com/questions/74523441/nested-functions-in-o
- [ ] Look into go routines for filling up an array. - [ ] Look into go routines for filling up an array.
- [ ] Anonymous functions for nested: https://stackoverflow.com/questions/74523441/nested-functions-in-o - Mhh, it's different from threads.

View File

@ -84,6 +84,12 @@ func sample_mixture(fs []func64, weights []float64) float64 {
} }
func slice_fill(xs []float64, fs func64) {
for i := range xs {
xs[i] = fs()
}
}
func main() { func main() {
var p_a float64 = 0.8 var p_a float64 = 0.8
var p_b float64 = 0.5 var p_b float64 = 0.5
@ -97,6 +103,27 @@ func main() {
fs := [4](func64){sample_0, sample_1, sample_few, sample_many} fs := [4](func64){sample_0, sample_1, sample_few, sample_many}
var n_samples int = 1_000_000 var n_samples int = 1_000_000
var xs = make([]float64, n_samples)
var xs0 = xs[0:250_000]
var xs1 = xs[250_000:500_000]
var xs2 = xs[500_000:750_000]
var xs3 = xs[750_000:1_000_000]
model := func() float64 { return sample_mixture(fs[0:], ws[0:]) }
slice_fill(xs0, model)
slice_fill(xs1, model)
slice_fill(xs2, model)
slice_fill(xs3, model)
var avg float64 = 0
for _, x := range xs {
avg += x
}
avg = avg / float64(n_samples)
fmt.Printf("Average: %v\n", avg)
/*
var avg float64 = 0 var avg float64 = 0
for i := 0; i < n_samples; i++ { for i := 0; i < n_samples; i++ {
avg += sample_mixture(fs[0:], ws[0:]) avg += sample_mixture(fs[0:], ws[0:])
@ -104,4 +131,5 @@ func main() {
avg = avg / float64(n_samples) avg = avg / float64(n_samples)
fmt.Printf("Average: %v\n", avg) fmt.Printf("Average: %v\n", avg)
*/
} }