浮点算术的最佳实践 [英] Best practices for floating-point arithmetics

查看:164
本文介绍了浮点算术的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在表演的加法和减法是precise到小数点后第二位小数的输入。我试图把它们转换成整数,以提高准确性通过乘以100,但取得了相反的效果。

I was performing addition and subtraction on an input of decimals that are precise to the second decimal place. I tried to improve accuracy by converting them to integers through multiplying 100, but achieved opposite effects.

考虑以下code和输出:

Consider the following code and output:

double d = 2.01;
int a = (int) (d * 100.0);
cout << a << endl;

输出是:

200

一劳永逸,什么是一些与浮点算术的最佳实践?是它在所有可行的第一个双击转换为 INT 使用code的一些变种以上,然后铸造回来?

Once and for all, what are some of the best practices regarding floating-point arithmetics? Is it at all feasible to first convert the double to an int using some variant of the code above, and then casting it back?

推荐答案

如果您打印出 D * 100.0 来(说)20位小数,问题的结果将很快变得明显:

If you print out the result of d*100.0 to (say) 20 decimal places, the problem will quickly become apparent:

200.99999999999997

由于这是(有一每分钟)不足201,它被截断到200,当你转换为 INT

最明显的解决方法是强制四舍五入。至少如果你输入的都是积极的,可以作为增加0.5到结果一样简单:

The obvious cure is to force rounding. At least if your inputs are all positive that can be as simple as adding 0.5 to the result:

int a = (int)(d*100.0 + 0.5);

如果你可以在你的编译器支持指望它,它更容易使用标准库的圆形

If you can count on your compiler supporting it, it's even easier to use the standard library's round:

long a = lround(d*100.0);

这正常工作为正数和负数。

This works correctly for both positive and negative numbers.

这篇关于浮点算术的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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