Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ float into Python float wrong conversion

Tags:

c++

python

swig

I'm using SWIG to wrap my C++ code into Python. But the conversion of floating point numbers is strange. For example, if I have the function below (written in C++)

float foo() {
    float x=62.02;
    return x;
}

and executes it (after wrapping with SWIG) in Python

>>> import mymodule
>>> mymodule.foo()
62.02000045776367
>>>

it returns 62.02000045776367 instead of 62.02.

Is there a way to tell SWIG how to make the right conversion?

like image 672
Caio S. Souza Avatar asked Feb 04 '26 04:02

Caio S. Souza


1 Answers

This is the correct conversion, it's just that you cannot represent the decimal 62.02 precisely with a float, much like you cannot represent the fraction 2/3 in decimal.

You can see a little more with this short code, where you will see what C++ sees when you store 62.02 as both float and double: http://ideone.com/HvfZb

like image 192
Seth Carnegie Avatar answered Feb 05 '26 18:02

Seth Carnegie