GO:操作随机生成的float64

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

GO: manipulating random generated float64

问题

我想知道我们是否可以指定随机生成器在小数点后生成多少个数字?

默认行为示例:

fmt.Println(rand.float64())

将打印出数字0.6046602879796196

期望的行为:

fmt.Println(rand.float64(4))

然后将打印出数字0.6047。

这个功能在GO中是否已经存在,还是我需要自己实现?

谢谢!

英文:

I was wondering if we can specify to the random generator to how many numbers should be generated after the point decimal?

Example of default behaviour:

fmt.Println(rand.float64())

Would print out the number 0.6046602879796196

Desired behaviour:

fmt.Println(rand.float64(4))

Would then print out the number 0.6047.

Does this functionality already exist in GO or would I have to implement it myself ?

Thank you!

答案1

得分: 2

看起来对你来说只有字符串表示很重要,而 fmt 包可以为你提供这个功能:

fmt.Printf("%1.4f", rand.Float64())

所以是的,你仍然需要包装这个调用来指定小数点后的位数。

func RandomDigits(number int) string {
    return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
}
英文:

It sounds like only the string representation is important to you, and the fmt package does provide that for you:

fmt.Printf("%1.4f", rand.Float64())

So yes, you would still need to wrap this call to specify the number of digits after the decimal point.

func RandomDigits(number int) string {
    return fmt.Sprintf("%1." + strconv.Itoa(number) + "f", rand.Float64())
}

答案2

得分: 2

我不知道这样的函数,但是你可以很容易地自己实现它。以下是一个示例代码:

// 将数字 x 截断为 n 位小数
//
// +- Inf -> +- Inf; NaN -> NaN
func truncate(x float64, n int) float64 {
    return math.Trunc(x * math.Pow(10, float64(n))) * math.Pow(10, -float64(n))
}

将数字向左移动 n 位小数,截断小数位,再将数字向右移动 n 位。

如果你想将数字呈现给用户,那么在某个时候你需要将数字转换为字符串。在这种情况下,你不应该使用上述方法,而应该使用字符串格式化,如 Tyson 所指出的。例如,由于浮点数是不精确的,可能会出现舍入误差:

truncate(0.9405090880450124, 3) // 0.9400000000000001
英文:

I don't know of such function, however it is easy to implement by yourself (play):

// Truncate the number x to n decimal places
//
// +- Inf -> +- Inf; NaN -> NaN
func truncate(x float64, n int) float64 {
	return math.Trunc(x * math.Pow(10, float64(n))) * math.Pow(10, -float64(n))
}

Shift the number n decimal places to the left, truncate decimal places, shift the number n places to the right.

In case you want to present your number to the user then you will, at one point, convert the number
to a string. When you do that, you should not use this method and instead use string formatting as pointed
out by Tyson. For example, as floating point numbers are imprecise there might be rounding errors:

truncate(0.9405090880450124,3) // 0.9400000000000001

huangapple
  • 本文由 发表于 2014年1月20日 02:10:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/21220587.html
匿名

发表评论

匿名网友

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

确定