Skip to content

Instantly share code, notes, and snippets.

@jfuerth
Created April 12, 2013 14:34
Show Gist options
  • Select an option

  • Save jfuerth/5372442 to your computer and use it in GitHub Desktop.

Select an option

Save jfuerth/5372442 to your computer and use it in GitHub Desktop.
A simple Java program for exploring the distance between consecutive values of type double. See the comment below for a formatted example of what this program outputs.
public class DoubleTrouble {
public static void main(String[] args) {
long actualValue = 10000000000000001L;
//long actualValue = 9999999999999999L;
//long actualValue = Long.MAX_VALUE;
double d = actualValue;
System.out.println("Exact value: " + actualValue);
System.out.println("Nearest double: " + (long) d);
double nextUp = Math.nextAfter(d, Double.POSITIVE_INFINITY);
double nextDown = Math.nextAfter(d, Double.NEGATIVE_INFINITY);
System.out.println("Next larger double value: " + nextUp + " .. distance = " + (nextUp - d));
System.out.println("Next smaller double value: " + nextDown + " .. distance = " + (nextDown - d));
}
}
@jfuerth
Copy link
Copy Markdown
Author

jfuerth commented Apr 12, 2013

When actualValue = 10000000000000001L, this program outputs:

Exact value:    10000000000000001
Nearest double: 10000000000000000
Next larger double value:  1.0000000000000002E16 .. distance = 2.0
Next smaller double value: 9.999999999999998E15 .. distance = -2.0

When actualValue = Long.MAX_VALUE, this program outputs:

Exact value:    9223372036854775807
Nearest double: 9223372036854775807
Next larger double value:  9.223372036854778E18 .. distance = 2048.0
Next smaller double value: 9.2233720368547748E18 .. distance = -1024.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment