向浮动中添加最小的浮动 [英] Adding smallest possible float to a float

查看:68
本文介绍了向浮动中添加最小的浮动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将浮点数的最小可能值添加到浮点数。因此,例如,我尝试这样做以获得1.0 +最小的浮点数:

I want to add the smallest possible value of a float to a float. So, for example, I tried doing this to get 1.0 + the smallest possible float:

float result = 1.0f + std::numeric_limits<float>::min();

但是这样做之后,我得到以下结果:

But after doing that, I get the following results:

(result > 1.0f) == false
(result == 1.0f) == true

我正在使用Visual Studio2015。为什么会发生这种情况?我该怎么办才能解决这个问题?

I'm using Visual Studio 2015. Why does this happen? What can I do to get around it?

推荐答案

如果您想要1之后的下一个可表示值,则可以使用该函数称为 std :: nextafter ,来自< cmath> 标头。

If you want the next representable value after 1, there is a function for that called std::nextafter, from the <cmath> header.

float result = std::nextafter(1.0f, 2.0f);

它从第一个参数开始向第二个参数的方向返回下一个可表示的值。因此,如果要查找下一个小于1的值,可以执行以下操作:

It returns the next representable value starting from the first argument in the direction of the second argument. So if you wanted to find the next value below 1, you could do this:

float result = std::nextafter(1.0f, 0.0f);

将最小的正可表示值添加到1无效,因为1与下一个可表示的值之差值大于0与下一个可表示值之间的差。

Adding the smallest positive representable value to 1 doesn't work because the difference between 1 and the next representable value is greater than the difference between 0 and the next representable value.

这篇关于向浮动中添加最小的浮动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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