in nearest rounding mode scalbn could introduce double rounding error when an intermediate value and the final result were both in the subnormal range e.g. scalbn(0x1.7ffffffffffffp-1, -1073) returned 0x1p-1073 instead of 0x1p-1074, because the intermediate computation got rounded to 0x1.8p-1023. with the fix an intermediate value can only be in the subnormal range if the final result is 0 which is correct even after double rounding. (there still can be two roundings so signals may be raised twice, but that's only observable with trapping exceptions which is not supported.)
32 lines
477 B
C
32 lines
477 B
C
#include <math.h>
|
|
#include <stdint.h>
|
|
|
|
float scalbnf(float x, int n)
|
|
{
|
|
union {float f; uint32_t i;} u;
|
|
float_t y = x;
|
|
|
|
if (n > 127) {
|
|
y *= 0x1p127f;
|
|
n -= 127;
|
|
if (n > 127) {
|
|
y *= 0x1p127f;
|
|
n -= 127;
|
|
if (n > 127)
|
|
n = 127;
|
|
}
|
|
} else if (n < -126) {
|
|
y *= 0x1p-126f * 0x1p24f;
|
|
n += 126 - 24;
|
|
if (n < -126) {
|
|
y *= 0x1p-126f * 0x1p24f;
|
|
n += 126 - 24;
|
|
if (n < -126)
|
|
n = -126;
|
|
}
|
|
}
|
|
u.i = (uint32_t)(0x7f+n)<<23;
|
|
x = y * u.f;
|
|
return x;
|
|
}
|