Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate over every possible double value

Tags:

java

primitive

Consider the case where you want to test every possible input value. Creating a case where you can iterate over all the possible ints is fairly easy, as you can just increment the value by 1 and repeat.

How would you go about doing this same idea for all the possible double values?

like image 411
user321605 Avatar asked Dec 27 '11 21:12

user321605


People also ask

Can we use double data type in for loop?

Using a double in a for loop requires careful consideration since repeated addition of a constant to a floating point can cause accumulating total to "go off" due to inexact conversions from decimal to binary.

How do you do double increment in a for loop?

the best things in life are simple. x = 12; // or some arbitruary value for( int i = 0; i < 10; i++, x++ ) { // Code... }

Can you iterate over sets?

There is no way to iterate over a set without an iterator, apart from accessing the underlying structure that holds the data through reflection, and replicating the code provided by Set#iterator...


1 Answers

You can iterate over all possible long values and then use Double.longBitsToDouble() to get a double for each possible 64-bit combination.

Note however that this will take a while. If you require 100 nanoseconds of processing for each double value it will take roughly (not all bit combinations are different double numbers, e.g. NaN) 2^64*1e-7/86400/365 years which is more than 16e11/86400/365 = 50700 years on a single CPU. Unless you have a datacenter to do the computation, it is a better idea to go over possible range of all input values sampling the interval at a configurable number of points.

Analogous feat for float is still difficult but doable: assuming you need 10 milliseconds of processing for each input value you need roughly 2^32*1e-2/86400 = 497.1 days on a single CPU. You would use Float.intBitsToFloat() in this case.

like image 152
Adam Zalcman Avatar answered Oct 13 '22 05:10

Adam Zalcman