Skip to content

Instantly share code, notes, and snippets.

@pholser
Created December 19, 2014 15:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pholser/9bad3b99ceacda17b4d3 to your computer and use it in GitHub Desktop.
Save pholser/9bad3b99ceacda17b4d3 to your computer and use it in GitHub Desktop.
package com.pholser;
import static java.lang.Float.*;
import static java.lang.Math.*;
public class FloatingPointFun {
public static void main(String[] args) {
showFloats();
}
private static void showFloats() {
int lastExponent = Integer.MIN_VALUE;
System.out.printf("Floats:\n====\n");
for (float f = -Float.MAX_VALUE; f <= Float.MAX_VALUE; f = Math.nextUp(f)) {
int exponent = getExponent(f);
if (exponent != lastExponent) {
if (f != -Float.MAX_VALUE)
show(Math.nextDown(f));
show(f);
lastExponent = exponent;
}
}
show(Float.MAX_VALUE);
show(Math.nextAfter(0F, Float.NEGATIVE_INFINITY));
show(Math.nextAfter(0F, Float.POSITIVE_INFINITY));
show(-0F);
show(0F);
show(Float.NaN);
show(Float.NEGATIVE_INFINITY);
show(Float.POSITIVE_INFINITY);
System.out.println();
}
private static void show(float f) {
System.out.printf("%.20E: exponent = %d, bits = %s, ulp = %.20E\n",
f,
getExponent(f),
bits(f),
ulp(f));
}
private static String bits(float f) {
return String.format("%32s", Integer.toBinaryString(floatToIntBits(f))).replace(' ', '0');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment