Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I expect float variable values that I set from literal constants to be unchanged after assignment to other variables?

If I do something like this:

float a = 1.5f;
float b = a;

void func(float arg)
{
  if (arg == 1.5f) printf("You are teh awresome!");
}

func(b);

Will the text print every time (and on every machine)?

EDIT

I mean, I'm not really sure if the value will pass through the FPU at some point even if I'm not doing any calculations, and if so, whether the FPU will change the binary representation of the value. I've read somewhere that the (approximate) same floating point values can have multiple binary representations in IEEE 754.

like image 913
GhassanPL Avatar asked Dec 22 '22 08:12

GhassanPL


1 Answers

First of all 1.5 can be stored accurately in memory so for this specific value, yes it will always be true.

More generally I think that the inaccuracies only pop up when you're doing computations, if you just store a value even if it doesn't have an accurate IEEE representation it will always be mapped to the same value (so 0.3 == 0.3 even though 0.3 * 3 != 0.9).

like image 80
Motti Avatar answered May 10 '23 14:05

Motti