views:

42

answers:

4

How can I list all possible values of a floating-point data type? I can do this using a union in C or C++ but will that be portable?

How can this be done in other languages? Javascript?

Let's just assume I am using this iteration to map theta to sin(theta).

+1  A: 

I cannot think of an portable way to do this. But given a 64 bit representation (standard IEEE double) and assuming that generating one value would take one nanosecond it would take more than 500 years to generate all possible values. So you have plenty of time to think of an algorithm :) ...

MartinStettner
+1  A: 

The union approach isn't quite portable. It depends on the size of whatever types you use. (If sizeof(your_fp_type) > sizeof(your_int_type), then you won't be able to iterate over the whole range, even if you had the time.)

Either way you go, realize that the possible floating point values aren't evenly distributed through the range of whatever type you choose. The difference between values gets bigger as you move away from 0. Considering that, and the time it'd take to generate such a list, and the fact that you don't even have enough HD space to represent every possible double (I guarantee you don't!), let alone RAM...I have to question the value of creating such a list. Looking up the value would take longer than just doing the calculation.

cHao
+1  A: 

How can I list all possible values of a floating-point data type?

By bit-twiddling the IEEE-754 representation of your float value, for a float you need 2^32 different representations assuming 4 Bytes per float would require 16GB of memory.

I assume you need a lookup table for the sine function, simply loop from 0 to 2*PI in steps of your required precision.

stacker
How do I twiddle the bits of a floating-point data type?
Vulcan Eager
stacker
@stacker, twiddle_float.c(6) : error C2296: '>>' : illegal, left operand has type 'float'
Vulcan Eager
@Vulcan Eager use casts like: unsigned fval = (unsigned) floatval
stacker
@stacker, There is no platform independent guarantee that unsigned and float are the same size.
Vulcan Eager
For sine, 0 to PI/2 is sufficient for a lookup table...
R..
+1  A: 

Take a look at the man pages for nextafter() and nextafterf(). They let you advance from a floating point number to the next closest one. You could use one of these to visit each FP number in order.

John Gordon