Printing double without losing precision

后端 未结 7 1157
一整个雨季
一整个雨季 2020-12-01 03:44

How do you print a double to a stream so that when it is read in you don\'t lose precision?

I tried:

std::stringstream ss;

double v = 0.1 * 0.1;
ss          


        
相关标签:
7条回答
  • 2020-12-01 04:12

    @ThomasMcLeod: I think the significant digit rule comes from my field, physics, and means something more subtle:

    If you have a measurement that gets you the value 1.52 and you cannot read any more detail off the scale, and say you are supposed to add another number (for example of another measurement because this one's scale was too small) to it, say 2, then the result (obviously) has only 2 decimal places, i.e. 3.52. But likewise, if you add 1.1111111111 to the value 1.52, you get the value 2.63 (and nothing more!).

    The reason for the rule is to prevent you from kidding yourself into thinking you got more information out of a calculation than you put in by the measurement (which is impossible, but would seem that way by filling it with garbage, see above).

    That said, this specific rule is for addition only (for addition: the error of the result is the sum of the two errors - so if you measure just one badly, though luck, there goes your precision...).

    How to get the other rules: Let's say a is the measured number and δa the error. Let's say your original formula was: f:=m a Let's say you also measure m with error δm (let that be the positive side). Then the actual limit is: f_up=(m+δm) (a+δa) and f_down=(m-δm) (a-δa) So, f_up =m a+δm δa+(δm a+m δa) f_down=m a+δm δa-(δm a+m δa) Hence, now the significant digits are even less: f_up ~m a+(δm a+m δa) f_down~m a-(δm a+m δa) and so δf=δm a+m δa If you look at the relative error, you get: δf/f=δm/m+δa/a

    For division it is δf/f=δm/m-δa/a

    Hope that gets the gist across and hope I didn't make too many mistakes, it's late here :-)

    tl,dr: Significant digits mean how many of the digits in the output actually come from the digits in your input (in the real world, not the distorted picture that floating point numbers have). If your measurements were 1 with "no" error and 3 with "no" error and the function is supposed to be 1/3, then yes, all infinite digits are actual significant digits. Otherwise, the inverse operation would not work, so obviously they have to be.

    If significant digit rule means something completely different in another field, carry on :-)

    0 讨论(0)
提交回复
热议问题