英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论