如何改变一个浮动其最小增量(或接近)? [英] How to alter a float by its smallest increment (or close to it)?

查看:140
本文介绍了如何改变一个浮动其最小增量(或接近)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个双击˚F,并想办法轻推它非常略大(或更小)得到一个新的值,就可以尽可能接近原来的,但仍严格大于(或小于)原始

I have a double value f and would like a way to nudge it very slightly larger (or smaller) to get a new value that will be as close as possible to the original but still strictly greater than (or less than) the original.

它没有接近到最后位它是更重要的变化无论我做保证,以产生不同的值,而不是本轮回到原来的。

It doesn't have to be close down to the last bit—it's more important that whatever change I make is guaranteed to produce a different value and not round back to the original.

推荐答案

检查math.h中的文件。如果你很幸运,你有 函数nextafter nextafterf 功能定义。他们做的正是你想在一个便携式和平台无关的方式是什么,因此C99标准的一部分。

Check your math.h file. If you're lucky you have the nextafter and nextafterf functions defined. They do exactly what you want in a portable and platform independent way and are part of the C99 standard.

另一种方式来做到这一点(可能是一个备用解决方案)是分解的浮到尾数和指数的一部分。递增非常简单:只需加一个尾数。如果你得到溢出你必须通过增加你的指数来处理这个问题。递减的工作方式相同。

Another way to do it (could be a fallback solution) is to decompose your float into the mantissa and exponent part. Incrementing is easy: Just add one to the mantissa. If you get an overflow you have to handle this by incrementing your exponent. Decrementing works the same way.

修改:正如评论指出,这足以只是增加了浮在它的二进制重新presentation。尾数溢出将增加指数,而这正是我们想要的。

EDIT: As pointed out in the comments it is sufficient to just increment the float in it's binary representation. The mantissa-overflow will increment the exponent, and that's exactly what we want.

这是概括地说是函数nextafter做同样的事情。

That's in a nutshell the same thing that nextafter does.

这不会是完全可移植的,但。你将不得不处理字节序的事实是,并非所有的机器确实有IEEE浮点数(OK - 最后的原因是更多的学术)

This won't be completely portable though. You would have to deal with endianess and the fact that not all machines do have IEEE floats (ok - the last reason is more academic).

另外处理楠和infinites可以是一个有点棘手。你不能简单地增加他们,因为他们被定义不是数字。

Also handling NAN's and infinites can be a bit tricky. You cannot simply increment them as they are by definition not numbers.

这篇关于如何改变一个浮动其最小增量(或接近)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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