如何在Go中分配一个浮点数切片?

huangapple go评论97阅读模式
英文:

How to allocate a slice of floats in Go?

问题

我正在学习Go编程,并尝试测试以下的average函数:

func average(xs []float64) float64 {
    total := 0.0
    for _, v := range xs {
        total += v
    }
    return total / float64(len(xs))
}

我尝试通过以下方式生成一个随机浮点数的切片:

var xs []float64
for n := 0; n < 10; n++ {
    xs[n] = rand.Float64()
}

然而,我得到了以下错误:

panic: runtime error: index out of range

问题:

  1. 如何在Go中生成一个随机数的切片?
  2. 在切片字面量中,是否允许使用表达式或函数调用,例如xs := []float64 { for ... }
英文:

I'm learning Go programming and try to test the following average function:

func average(xs []float64) float64 {
    total := 0.0
    for _, v := range xs {
	    total += v
    }
    return total / float64(len(xs))
}

I tried to generate a slice of random float numbers by:

var xs []float64
for n := 0; n &lt; 10; n++ {
    xs[n] = rand.Float64()
}

however, I got

panic: runtime error: index out of range

Question:

  1. How to generate a slice of random number in Golang?
  2. Is expression or function call, like xs := []float64 { for ... } allowed in slice literals?

答案1

得分: 9

你生成随机数的方法是正确的,但是xs是空的,而Go语言不会自动扩展切片。你可以使用append函数,但是由于你事先知道大小,最高效的方法是将

var xs []float64

替换为

xs := make([]float64, 10)

这样切片在初始时就会有正确的大小。

英文:

Your method of generating the random numbers is fine, however xs is empty, and Go doesn't automatically extend slices. You could use append, however since you know the size in advance, it's most efficient to replace

var xs []float64

with

xs := make([]float64, 10)

which will give it the right size initially.

答案2

得分: 4

@hobbs回答了关于你的错误的部分,但是你的解决方案每次运行时都会给你相同的数组,因为你没有传递一个随机种子。我会这样做:

package main 

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

func main() {
	s := rand.NewSource(time.Now().UnixNano())
	r := rand.New(s)

	xn := make([]float64, 10)

	for n := 0; n < 10; n++ {
		xn[n] = r.Float64()
	}

	fmt.Println(xn)
}

这样你每次运行程序时都会得到不同的数组。

英文:

@hobbs answered the part about your error, but still your solution will give you the same array every time you run it because you are not passing a random seed. I would do something like this:

package main 

import (
	&quot;fmt&quot;
	&quot;math/rand&quot;
	&quot;time&quot;
)

func main() {
	s := rand.NewSource(time.Now().UnixNano())
	r := rand.New(s)

	xn := make([]float64, 10)

	for n := 0; n &lt; 10; n++ {
		xn[n] = r.Float64()
	}

	fmt.Println(xn)
}

huangapple
  • 本文由 发表于 2015年11月10日 22:30:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/33632365.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定