Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Floating point changes %d value every time executed

I tried to print float using %d (I know that this shouldn't be done. But every time re-run executable it gives out a different value)
My question is : Why does the printed value changes every time ? My System : Ubuntu 14.04 (64 bit) Compiler : 4.8.4 Here is the code:

#include<stdio.h>

int main(){
  float b = 12.3456;

  printf("%d\n",b);

}

Sample output:

4bh1@mybox:~/C-fi$ ./test 
-1629995944
4bh1@mybox:~/C-fi$ ./test 
1147348376
4bh1@mybox:~/C-fi$ ./test 
-1746005432
4bh1@mybox:~/C-fi$ ./test 
510102216
4bh1@mybox:~/C-fi$ 
like image 758
4bh1 Avatar asked Jul 08 '16 12:07

4bh1


People also ask

Why do computers mess up floating point math?

Because JavaScript uses the IEEE 754 standard for Math, it makes use of 64-bit floating numbers. This causes precision errors when doing floating point (decimal) calculations, in short, due to computers working in Base 2 while decimal is Base 10.

Why are floating point numbers inaccurate?

Floating-point decimal values generally do not have an exact binary representation. This is a side effect of how the CPU represents floating point data. For this reason, you may experience some loss of precision, and some floating-point operations may produce unexpected results.

How accurate are floating point numbers?

With a data type, there is a limited number of bits. Those bits cannot accurately represent a value that requires more than that number of bits. The data type float has 24 bits of precision. This is equivalent to only about 7 decimal places.


1 Answers

Using the wrong format specifier for printf is a classic example of undefined behavior. That means the behavior is unpredictable and can't be depended on to be consistent from one run to the next. It could crash, it could print random values, or it could appear to work.

What's actually happening is an implementation detail of the compiler and architecture in question. But unless you're actually writing a compiler, there's not much use in digging into it.

If you're familiar with assembler, you could look at the compiled code to see what instructions it generated. Keep in mind however that different compilers (even the same compiler with different optimization settings) will most likely generate different assembly.

like image 105
dbush Avatar answered Nov 15 '22 12:11

dbush