如何将math/big.Int转换为float64?

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

How to convert math/big.Int to float64?

问题

我正在使用Go语言的big.Int作为长时间运行的服务中的计数器,其中统计计数器可能在长时间运行中溢出常规的uint64。偶尔我需要计算类似于“从程序开始以来的平均速率是多少?”这样的问题,需要进行除法运算,如float64(big.Int) / time.Since(beginning).Seconds();在速率计算中,转换时的精度损失是可以接受的。

但是这种float64(big.Int)的转换方法不起作用。
我看到该包中有一个big.Int.Uint64的转换方法,但如果值溢出常规的uint64,则该方法是未定义的。
我想知道为什么标准库没有提供一个Float64()方法,是否有任何解决方法可以获得浮点数值?

英文:

I'm using Go's big.Int as counters in a long running service where the statistics counters might overflow a regular uint64 over a long run. Occasionally I need to calculate something like, "what's the average rate since program beginning?", needing a division like float64(big.Int) / time.Since(beginning).Seconds(); the precision loss of conversion is acceptable in the rate calculation.

But this kind of float64(big.Int) conversion doesn't work.
I see the package has a
big.Int.Uint64
conversion method but it's undefined if the value overflows a regular uint64.
I wonder why the standard library doesn't provide a to Float64() method and is there any workaround how to get a floating point value?

答案1

得分: 22

你可以使用Float.SetInt方法将big.Int转换为big.Float

i := big.NewInt(12345)
f := new(big.Float).SetInt(i)

然后,你可以将f转换为具有所需精度的float64,或者使用big.Float的方法以更高的精度计算输出。

英文:

You can convert a big.Int to a big.Float using the Float.SetInt method.

i := big.NewInt(12345)
f := new(big.Float).SetInt(i)

Then you can either convert f as a float64 with the accepted accuracy, or use the big.Float methods to calculate the output with greater accuracy.

huangapple
  • 本文由 发表于 2017年2月28日 04:00:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/42494690.html
匿名

发表评论

匿名网友

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

确定