浮点和不是精确的 [英] Sum of float is not exact

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

问题描述

请考虑以下C ++程序:

Consider the following C++ program:

#include <iostream>
using std::cout;
using std::endl;

int main () {
   float x = 0.0001;
   float y = 0;
   for (int i=0; i < 10000; i++) {
      y += x;
   }
   cout << y << endl;
   return 0;
}

编译并运行此程序,然后回答以下问题:
该程序的实际行为与预期行为有何不同?

Compile and run this program and then answer the following questions: How does the actual behaviour of this program differ from its expected behaviour?

为什么看不到预期的行为?

Why is the expected behaviour not seen?

在确保程序语义保持不变的同时,您对此程序进行哪些更改以确保预期和实际行为匹配?

While ensuring that the program semantics stay the same, what changes would you make to this program to ensure that the expected and the actual behaviour do match?

以上是我的作业。我知道我想做我自己的家庭作业,但我被困。

The above is my assignment. I know I am suppose to do my own homework but I'm stuck.


  • 对于a)数字是不同的。

  • For part a) I simply said the 2 numbers are different.

对于c)部分,我把float变成了double。 (我认为语义保持不变)

For part c) I made the float into a double. (I think the semantic stays the same)

对于b部分,我知道这被称为灾难性的取消,但是prof可能想看到更多,我不知道还有什么要说的。有人可以帮助我吗?

For part b) I know this is called catastrophic cancellation, but the prof probably wants to see more than that and I have no idea what else to say. Can someone help me?

感谢您的帮助

推荐答案

此程序的实际行为与预期行为有何不同?
- 这个程序的实际行为是将0.0001的IEEE表示增加10000次; IEEE表示0.0001!=实际0.0001

How does the actual behaviour of this program differ from its expected behaviour? -The actual behaviour of this program is adding up IEEE representation of 0.0001 up 10000 times; IEEE representation of 0.0001 != actual 0.0001

为什么看不到预期的行为?
- 我们假设0.0001正好表示为0.0001,不是真正的,因为IEEE浮点不能精确地表示0.0001,因为必须表示base2而不是base10中的所有浮点。

Why is the expected behaviour not seen? -We assume 0.0001 is exactly represented as 0.0001, in realty it isn't since IEEE floating points can't represent 0.0001 exactly due to having to represent all floating points in base2 instead of base10.

在确保程序语义保持不变的同时,你对这个程序做了什么改变,以确保预期和实际行为匹配?
- 在这种情况下,悬浮浮动double将工作,因为double给你更多的小数精度比float。
- 替代解决方案是保持浮动,而不是求和,你分配y = 10000 * x(这会导致更少的错误,它是更好的,当你寻找避免roundoff和近似错误)

While ensuring that the program semantics stay the same, what changes would you make to this program to ensure that the expected and the actual behaviour do match? -Changing float to double will work in this case, because double gives you more decimal precision than float. -Alternative solution is to keep float and instead of doing summation, you assign y = 10000*x (this incurs less error and it's better when you're looking to avoid roundoff and approximation errors)

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

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