为浮点值分配一个确切的表示 [英] Assigning an exact representation to a floating point value

查看:173
本文介绍了为浮点值分配一个确切的表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题,OP试图隔离一个大程序中难以捉摸的错误。他观察了一些 double 值,然后试图将它们作为输入硬编码到一个更小的测试程序中。这个方法是很好的隔离这样一个bug。

所选择的方法违反了字符串别名规则,引入了UB,因此测试是完全不可靠的:


  1. 在调试器中监视表达式:

    $ $ $ $ $ $ $ $ $ + ------------------------ + ---------------------- |
    |观看表达式|值|
    + ------------------------ + -------------------- - |
    | *(long long int *)(& a)| 4594681439063077250 |
    + ------------------------ + -------------------- - |


  2. 然后在测试程序中分配:

      double a; 
    *(long long int *)(& a)= 4594681439063077250;


(我非常怀疑)为了保存确切的 double 值,一点一滴的。

问题:如何在调试会话中观察到
的精确值 - 按位分配 -

解决方案

一个十六进制表示法是一个很好的方法来分配一个浮点值的精确位表示。如果因为您还没有使用C ++ 17而无法使用文字,请注意,strtod可以识别这种格式。


In this question the OP tried to isolate an elusive bug in a big program. He observed some double values and then tried to hard code them as input to a smaller test program. The ideea is great for isolating such a bug.

The method chosen however violates the String Aliasing rule, introducing UB, thus the test is completely unreliable:

  1. watch in debugger the expression:

    +------------------------+----------------------|
    | Watch Expression       | Value                |
    +------------------------+----------------------|
    | *(long long int *)(&a) | 4594681439063077250  |
    +------------------------+----------------------|
    

  2. and then assign it in the test program:

    double a;
    *(long long int *)(&a) = 4594681439063077250;
    

(I strongly suspect) He did this in order to preserve the exact double value, bit by bit.

The question: How to assign to a double the exact value - bit by bit - observed in a debug session?

解决方案

Hexadecimal representation is a good way to assign the exact bit representation of a floating point value. If you cannot use literals because you are not yet on C++ 17, note that strtod recognizes this format.

这篇关于为浮点值分配一个确切的表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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