Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alter a float by its smallest increment (or close to it)?

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.

like image 887
Owen Avatar asked Sep 30 '08 22:09

Owen


People also ask

How do I assign a number to a float?

Assigning Values (Putting Information in the Float Variables) You can then change the float value by assigning a value to the variable. (Just like you did with integers.) This is done simple by writing the variable name followed by an equals sign, followed by the value you want to put in the variable.

How do you float variables?

You can define a variable as a float and assign a value to it in a single declaration. For example: float age = 10.5; In this example, the variable named age would be defined as a float and assigned the value of 10.5.

Is 1.5 float or double?

And the reason the comparison succeeds with 1.5 is that 1.5 can be represented exactly as a float and as a double ; it has a bunch of zeros in its low bits, so when the promotion adds zeros the result is the same as the double representation.


1 Answers

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.

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.

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

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).

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

like image 167
Nils Pipenbrinck Avatar answered Oct 09 '22 13:10

Nils Pipenbrinck