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?
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
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 .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.