Jul_DW
Jul_DW

Reputation: 1064

ULP calculation floating-point

I'm currently writing a "new language" at school, and I have to implement a Math class.

One of the specifications is to implement ulp method, like Math.ulp() in Java. We are working on float types.

I found many interesting sources, but I'm still not able to calculate ulp of a float..

AFAIK, if

normalized x

then

ulp equation

But, how can I get this normalized form for a float without any lib ? And how to get parameters e & n+1 ?

Thank you for your help,

Best regards,

Upvotes: 0

Views: 1474

Answers (1)

Paul Stelian
Paul Stelian

Reputation: 1379

I'm not sure Java has the possibility of aliasing to get the bit pattern of the floating point number (there is a close enough alternative, as the second part of the answer shows), but if it does, then e is the bits 23 through 30 (31 is sign) minus some constant (as in the wikipedia description of the format, it's 127 unless the number is subnormal) while n is fixed (in this case it's 23 bits, or 24 if it includes the implicit 1)

It's recommended you use a lib that does this job for you properly.

Another option I've been notified in the comments of (rather indirectly) implies converting the float bits to int. I will write a snippet of code directly. I'm not fully versed in Java (the code may not work immediately due to lacking package/class specifiers (floatToIntBits as well as intToFloatBits are static methods of the class java.lang.Float). This is different from the above suggestion since it's a bit unorthodox but it has better performance than the code you suggested in the question itself.

float ulp(float x) {
    int repr;
    float next;
    if (Float.isNaN(x)) return Float.NaN; //special handling, to be safe
    repr = Float.floatToIntBits(x);
    x++; //will work correctly independently of sign
    next = Float.intBitsToFloat(repr)
    return next-x;
}

Upvotes: 2

Related Questions