简体   繁体   中英

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

归一化x

then

ulp方程

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,

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM