将double乘以整数精度 [英] multiplication of double with integer precision

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

问题描述

我有3.4的两倍.但是,当我将其乘以100时,它得到的是339,而不是340.这似乎是由于double的精度引起的.我该如何解决?

I have a double of 3.4. However, when I multiply it with 100, it gives 339 instead of 340. It seems to be caused by the precision of double. How could I get around this?

谢谢

推荐答案

首先发生的事情:

  1. 3.4不能完全表示为二进制分数.因此,实现选择可表示的最接近的二进制分数.我不确定它是否总是四舍五入,但是在您的情况下,表示的数字确实较小.
  2. 到整数截断的转换,即使用最接近的绝对值较小的整数 .
  3. 由于两个转换的方向相同,因此始终会产生舍入误差.
  1. 3.4 can't be represented exactly as binary fraction. So the implementation chooses closest binary fraction that is representable. I am not sure whether it always rounds towards zero or not, but in your case the represented number is indeed smaller.
  2. The conversion to integer truncates, that is uses the closest integer with smaller absolute value.
  3. Since both conversions are biased in the same direction, you can always get a rounding error.

现在,您需要知道所需的内容,但是可能要使用对称舍入,即找到最接近的整数(较小或较大).可以实现为

Now you need to know what you want, but probably you want to use symmetrical rounding, i.e. find the closest integer be it smaller or larger. This can be implemented as

#include <cmath>
int round(double x) { std::floor(x + 0.5); } // floor is provided, round not

int round(double x) { return x < 0 ? x - 0.5 : x + 0.5; }

我不确定完全将其舍入为零,因此如果您使用它,请稍后验证.

I am not completely sure it's indeed rounding towards zero, so please verify the later if you use it.

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

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