从指数和有效数创建浮点数 [英] Create float from exponent and significand

查看:109
本文介绍了从指数和有效数创建浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出整数exp0<=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用于诸如float32float64之类的浮点数的浮点算法(就像几乎任何其他语言一样).

The IEEE-754 standard defines the floating point arithmetics which Go uses for floating point numbers such as float32 and float64 (just like almost any other language).

由于有效位数最多为52位,因此显然只能使用float64值表示.

Since your significand may be up to 52 bits, obviously it can only be represented using a float64 value.

Double-精确浮点格式.

下面是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

(注意:expsig的类型应为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:

使用 offset-binary 编码双精度二进制浮点指数>表示,零偏移为1023;在IEEE 754标准中也称为指数偏差.

The double-precision binary floating-point exponent is encoded using an offset-binary representation, with the zero offset being 1023; also known as exponent bias in the IEEE 754 standard.

因此,以上述双精度格式编码的数字的计算方式如下:

So the number encoded in the above double-precision format is calculated like:

(-1) sign x 2 e-1023 x 1.fraction

(-1)sign x 2e-1023 x 1.fraction

这篇关于从指数和有效数创建浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆