Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send floating point numbers over network using google protobuf?

I have a proto file which has following message:

message MapInfo
{
    required float version = 1;
    required bool status = 2;
}

where, version is a float value. When I am sending float value 2.1 from c++ to python, at python side, it is deserialized as 2.09999990463.

Why is this so? Is there any specofic handling for float numbers?

Protoc compiler version and runtime protobuf library version is 2.4.1.

like image 594
garima721 Avatar asked Aug 05 '15 06:08

garima721


1 Answers

The value 2.1 cannot be represented exactly as a float. You can test this in a simple C++ program or a C++ debugger:

(gdb) print 2.1f
$1 = 2.0999999

Python, however, presents everything as doubles. Thus the float value received from C++ gets converted to the double that is nearest to 2.0999999..., not nearest to 2.1.

This is all just a consequence of the fact that not all decimal numbers are exactly representable as floats. In general, float numbers always have rounding errors and you cannot expect them to be exactly the correct value, just very close.

like image 91
jpa Avatar answered Oct 13 '22 21:10

jpa