问题描述
给出整数exp
和0<=sig<2^52
,如何创建以exp
为指数且有效位数与sig
的二进制表示形式相同的float64?(在Go中)?
Given integers exp
and 0<=sig<2^52
, how can I create the float64 with exp
as exponent and whose significand bits are the same as the binary representation of sig
(in Go)?
推荐答案
IEEE-754标准定义了Go用于诸如float32
和float64
之类的浮点数的浮点算法(就像几乎任何其他语言一样).
由于有效位数最多为52位,因此显然只能使用float64
值表示.
下面是float64
值的位的图片(摘自Wikipedia):
Here's a picture of the bits of a float64
value (taken from Wikipedia):
您声称自己具有指数值和有效位数(即小数部分).
You claim you have the exponent value and the significand (which is the fraction part).
您可以使用简单的按位算术来构造浮点的64位值,如下所示:
You may use simple bitwise arithmetic to construct the 64-bit value of the floating point like this:
bits := exp<<52 | sig
(注意:exp
和sig
的类型应为uint64
.否则,请使用类型转换.)
(Note: exp
and sig
should be of type uint64
. If not, use a type conversion.)
一旦有了这些位,就可以使用 math.Float64frombits()
函数来获取作为float64
值:
Once you have the bits, you may use the math.Float64frombits()
function to get it as a float64
value:
f := math.Float64frombits(bits)
请注意,内存布局的指数值不是计算数字值时必须使用的直接"数字,而是:
Note that the exponent value of the memory layout is not the "direct" number you have to use when calculating the value of the number, but:
因此,以上述双精度格式编码的数字的计算方式如下:
So the number encoded in the above double-precision format is calculated like:
这篇关于从指数和有效数创建浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!