Skip to content

Instantly share code, notes, and snippets.

@pholser
Created December 19, 2014 15:46
Show Gist options
  • Select an option

  • Save pholser/9bad3b99ceacda17b4d3 to your computer and use it in GitHub Desktop.

Select an option

Save pholser/9bad3b99ceacda17b4d3 to your computer and use it in GitHub Desktop.

Revisions

  1. pholser created this gist Dec 19, 2014.
    47 changes: 47 additions & 0 deletions FloatingPointFun.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,47 @@
    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');
    }
    }