Plomblem双精度 [英] Plomblem with double precision

查看:132
本文介绍了Plomblem双精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

double var = 79999.95;

cout<< var<< endl;



输出我得到的是79999.9,但我希望op为79999.95。我想要精确的precesion而不会四舍五入。我知道setprecision(2)会将输出打印为79999.95。但是因为我想使用该值(79999.95)进行进一步的计算,所以我如何得到val为79999.95,因为我认为setprecesion只打印价值。



我尝试过:



我试过< double = floor((val * 1000)+0.5)/ 1000; >

解决方案

浮点值有两点需要注意:

  1. 它们不能完全代表大多数值

  2. 打印值四舍五入到可能受上述影响的指定或默认分辨率

79999.95是第一个值的值之一点适用。它无法用 double 完全表示。存储的值为79999,949999999997,可通过设置相应的输出精度(17位有效数字)进行验证。对于单精度 float ,存储的值为79999,95313。



有限的分辨率和不准确性是对于简单的数学运算来说不是问题。但是,在可能累积舍入误差的复杂操作中,它可能会成为一个问题。然后算法实现必须处理这个。



当知道值本身的精度时,显示可能错误的舍入值的问题没有问题。你应该知道你的输入值。



相关读物:

浮点数指南 [ ^ ]

每个计算机科学家应该知道的关于浮点运算的内容 [ ^ ]


将其打印到字符串缓冲区中即可完成。

  char  s [ 20 ]; 
sprint(s, %0.2f,var);
cout<< s<< ENDL;


double var = 79999.95;
cout << var << endl;

output I m getting is 79999.9, But I want the op to be 79999.95. I want the accurate precesion without rounding off.I know that setprecision(2) will print the output as 79999.95.But since I want to use that value (79999.95)for further computation, So how can I get the val as 79999.95 ,since I think that setprecesion is only printing the value.

What I have tried:

I have tried of <double = floor((val * 1000) +0.5)/ 1000; >

解决方案

There are two things to observe with floating point values:

  1. They can not represent most values exactly
  2. Printed values are rounded to a specified or default resolution which might be affected by the above

79999.95 is one of the values where the first point applies. It can't be represented exactly with a double. The stored value is 79999,949999999997 which can be verified by setting a corresponding output precision (17 significant digits). For a single precision float, the stored value would be 79999,95313.

The limited resolution and inaccuracy is not a problem for simple mathematic operations. But it might become a problem with complex operations where rounding errors can accumulate. Then the algorithm implementation has to take care of that.

The problem of showing a probably wrong rounded value is no problem when knowing about the precision of the value itself. And you should know that for your input values.

Related reads:
The Floating-Point Guide[^]
What Every Computer Scientist Should Know About Floating-Point Arithmetic[^]


Print it into a string buffer and you are done.

char s[20];
sprint(s,"%0.2f",var);
cout << s << endl;


这篇关于Plomblem双精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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