C ++我刚读到,浮点是不精确的,不存储确切的整数值。这是什么意思? [英] C++ I've just read that floats are inexact and do not store exact integer values. What does this mean?

查看:139
本文介绍了C ++我刚读到,浮点是不精确的,不存储确切的整数值。这是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



将值为1的浮点数和值为1的整数不编译为(在此省略大量零)



0001



如果他们都编译到这里,那么这个不精确来到哪里。 p>

我使用的资源是 http:// www.cprogramming.com/tutorial/lesson1.html



感谢。

解决方案

这是可能的。浮点数以指数符号(a * 2 ^ n)表示,其中一些位表示a(有效位),并且一些位表示n(指数) 。



由于所谓的原子原则,您不能唯一地表示浮点值范围内的所有整数。例如,32位浮点数高达10 ^ 38,但在32位上,您只能表示2 ^ 32个值 - 这意味着一些整数将具有相同的表示。



现在,当您尝试执行以下操作时会发生什么:

  x = 10 ^ 38  - 10 ^ 38  -  1)

你应该得到1,但是你可能不会,因为10 ^ 38和10 ^ 38-1彼此非常接近,计算机必须以相同的方式表示它们。所以,你的1.0f通常是1,但如果这1是计算的结果,它可能不是。



这里是一些示例。


I am thinking of this at a binary level.

would a float of value 1 and an integer of value 1 not compile down to (omitting lots of zeros here)

0001

If they do both compile down to this then where does this inexactness come in.

Resource I'm using is http://www.cprogramming.com/tutorial/lesson1.html

Thanks.

解决方案

It's possible. Floating point numbers are represented in an exponential notation (a*2^n), where some bits represent a (the significand), and some bits represent n (the exponent).

You can't uniquely represent all the integers in the range of a floating point value, due to the so-called pigeonhole principle. For example, 32-bit floats go up to over 10^38, but on 32 bits you can only represent 2^32 values - that means some integers will have the same representation.

Now, what happens when you try to, for example, do the following:

x = 10^38 - (10^38 - 1)

You should get 1, but you probably won't, because 10^38 and 10^38-1 are so close to each other that the computer has to represent them the same way. So, your 1.0f will usually be 1, but if this 1 is a result of calculation, it might not be.

Here are some examples.

这篇关于C ++我刚读到,浮点是不精确的,不存储确切的整数值。这是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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