dongreng9864 2016-07-08 12:42
浏览 42
已采纳

生成n个不是∞或NaN的不同浮点数(在Go中)

I want a function getNthFloat(uint32 n) float32 such that for each n,m < 2³²-4 with n≠m, getNthFloat(n) and getNthFloat(m) return distinct floats that real numbers (neither NaN nor ±∞). 2³²-4 is chosen because if I understand IEEE 754 correctly, there are two binary representations of NaN, one for ∞ and one for -∞.

I imagine I should convert my uint32 into bits and convert bits into float32, but I can't figure out how to avoid the four values efficiently.

  • 写回答

2条回答 默认 最新

  • dongyouzhi7218 2016-07-08 13:04
    关注

    You can't get 2^32-4 valid floating point numbers in a float32. IEEE 754 binary32 numbers have two infinities (negative and positive) and 2^24-2 possible NaN values.

    A 32 bit floating point number has the following bits:

    31   30...23  22...0
    sign exponent mantissa
    

    All exponents with the value 0xff are either infinity (when mantissa is 0) or NaN (when mantissa isn't 0). So you can't generate those exponents.

    Then it's just a simple matter or mapping your allowed integers into this format and then use math.Float32frombits to generate a float32. How you do that is your choice. I'd probably be lazy and just use the lowest bit for the sign and then reject all numbers higher than 2^32 - 2^24 - 1 and then shift the bits around.

    So something like this (untested):

    func foo(n uint32) float32 {
        if n >= 0xff000000 {
            panic("xxx")
        }
        return math.Float32frombits((n & 1) << 31 | (n >> 1))
    }
    

    N.B. I'd probably also avoid denormal numbers, that is numbers with the exponent 0 and non-zero mantissa. They can be slow and might not be handled correctly. For example they could all be mapped to zero, there's nothing in the go spec that talks about how denormal numbers are handled, so I'd be careful.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟