Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Warning about data loss c++/c

Tags:

c++

c

visual-c++

I am getting a benign warning about possible data loss

warning C4244: 'argument' : conversion from 'const int' to 'float', possible loss of data

Question

I remember as if float has a larger precision than int. So how can data be lost if I convert from a smaller data type (int) to a larger data type (float)?

like image 553
Dr Deo Avatar asked Apr 17 '10 14:04

Dr Deo


2 Answers

Because float numbers are not precise. You cannot represent every possible value an int can hold into a float, even though the maximum value of a float is much higher.

For instance, run this simple program:

#include <stdio.h>

int main()
{
 for(int i = 0; i < 2147483647; i++)
 {
  float value = i;
  int ivalue = value;
  if(i != ivalue)
   printf("Integer %d is represented as %d in a float\n", i, ivalue);
 }
}

You'll quickly see that there are thousands billions of integers that can't be represented as floats. For instance, all integers between the range 16,777,219 and 16,777,221 are represented as 16,777,220.

EDIT again Running that program above indicates that there are 2,071,986,175 positive integers that cannot be represented precisely as floats. Which leaves you roughly with only 100 millions of positive integer that fit correctly into a float. This means only one integer out of 21 is right when you put it into a float.

I expect the numbers to be the same for the negative integers.

like image 198
zneak Avatar answered Oct 13 '22 15:10

zneak


On most architectures int and float are the same size, in that they have the same number of bits. However, in a float those bits are split between exponent and mantissa, meaning that there are actually fewer bits of precision in the float than the int. This is only likely to be a problem for larger integers, though.

On systems where an int is 32 bits, a double is usually 64 bits and so can exactly represent any int.

like image 24
JSBձոգչ Avatar answered Oct 13 '22 16:10

JSBձոգչ