Caio S. Souza
Caio S. Souza

Reputation: 151

C++ float into Python float wrong conversion

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?

Upvotes: 3

Views: 4530

Answers (2)

Seth Carnegie
Seth Carnegie

Reputation: 75150

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

Upvotes: 6

NPE
NPE

Reputation: 500683

Other than the lossless float->double conversion, there is no conversion going on.

62.02 cannot be represented exactly as a C float. The moment you do float x=62.02, the variable will contain the value that you mention.

I highly recommend reading What Every Computer Scientist Should Know About Floating-Point Arithmetic.

Upvotes: 4

Related Questions