Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C, is specifying 2.0f the same as 2.000000f?

Tags:

c

ieee-754

Are these lines the same?

float a = 2.0f;

and

float a = 2.000000f;
like image 899
Hải Phong Avatar asked Jan 05 '13 03:01

Hải Phong


3 Answers

Yes, it is. No matter what representation you use, when the code is compiled, the number will be converted to a unique binary representation. There's only one way of representing 2 in the IEEE 754 binary32 standard used in modern computers to represent float numbers.

like image 172
Sergiu Dumitriu Avatar answered Oct 21 '22 23:10

Sergiu Dumitriu


The only thing the C99 standard has to say on the matter is this (section 6.4.4.2):

For decimal floating constants ... the result is either the nearest representable value, or the larger or smaller representable value immediately adjacent to the nearest representable value, chosen in an implementation-defined manner.

That bit about "implementation-defined" means that technically an implementation could choose to do something different in each case. Although in practice, nothing weird is going to happen for a value like 2.

It's important to bear in mind that the C standards don't require IEEE-754.

like image 40
Oliver Charlesworth Avatar answered Oct 21 '22 23:10

Oliver Charlesworth


Yes, they are the same.

Simple check: http://codepad.org/FOQsufB4

int main() {
printf("%d",2.0f == 2.000000f);
}

^ Will output 1 (true)

like image 42
John Brodie Avatar answered Oct 21 '22 22:10

John Brodie