I'm playing around with floating-point arithmetic, and I encountered something which needs explaining.
When setting rounding mode to 'towards zero', aka:
fesetround(FE_TOWARDZERO);
And adding different kind of normal positive numbers, I can never reach Infinity.
However, it is known from the ieee 745 that overflow to infinity can result from adding finite numbers.
For instance:
#include <fenv.h>
#include <stdio.h>
float hex2float (int hex_num) {
return *(float*)&hex_num;
}
void main() {
int a_int = 0x7f7fffff; // Maximum finite single precision number, about 3.4E38
int b_int = 0x7f7fffff;
float a = hex2float(a_int);
float b = hex2float(b_int);
float res_add;
fesetround(FE_TOWARDZERO); // need to include fenv.h for that
printf("Calculating... %+e + %+e\n",a,b);
res_add = a + b;
printf("Res = %+e\n",res_add);
}
However, If i change rounding mode to something other, I might get a +INF as the answer.
Can someone explain this?
hex2float
does, as you don't even mention the library you are using. But I am pretty sure it is not takingint
s.. – Eugene Sh.hex2float
's definition is in the posted code. – Dolda2000hex
. – Eugene Sh.