dqqg0811 2017-09-10 02:58
浏览 25
已采纳

通过忽略golang中的最后一位来比较浮点数

A specification reads as follows:

It still considers real numbers equal if they differ in their last binary digit.

I would like to implement this way of comparing floats for the float64 data type in Go. Unfortunately, the bitwise operators aren't defined for floating point numbers. Is there a way to achieve this way of comparing floats in the Go language?

  • 写回答

2条回答 默认 最新

  • dongxiong4571 2017-09-10 05:36
    关注

    If you want to know if two float64 values are adjacent (that is, there's no float64 value between them):

    func almostEqual(a, b float64) bool {
        ai, bi := int64(math.Float64bits(a)), int64(math.Float64bits(b))
        return a == b || -1 <= ai-bi && ai-bi <= 1
    }
    

    Mostly that's the same as saying they differ in the lowest bit of their mantissa.

    This code doesn't work if a or b are NaNs, zeros or infinities, but you could add special cases if you wished.

    See https://randomascii.wordpress.com/2012/01/23/stupid-float-tricks-2/

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

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分