英文:
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
问题:
- 如何在Go中生成一个随机数的切片?
- 在切片字面量中,是否允许使用表达式或函数调用,例如
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 < 10; n++ {
xs[n] = rand.Float64()
}
however, I got
panic: runtime error: index out of range
Question:
- How to generate a slice of random number in Golang?
- 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 (
"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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论