C++ float 到 Python float 错误转换
我正在使用 SWIG 将 C++ 代码包装到 Python 中。但浮点数的转换却很奇怪。 例如,如果我有下面的函数(用 C++ 编写)
float foo() {
float x=62.02;
return x;
}
并在 Python 中执行它(用 SWIG 包装后),
>>> import mymodule
>>> mymodule.foo()
62.02000045776367
>>>
它将返回 62.02000045776367
而不是 62.02
。
有没有办法告诉 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是正确的转换,只是您无法使用
float
精确表示十进制62.02
,就像您无法表示分数2/3
一样> 以十进制表示。通过这段简短的代码,您可以看到更多内容,当您将
62.02
存储为float
和double
时,C++ 会看到什么:< a href="http://ideone.com/HvfZb" rel="nofollow">http://ideone.com/HvfZbThis is the correct conversion, it's just that you cannot represent the decimal
62.02
precisely with afloat
, much like you cannot represent the fraction2/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 bothfloat
anddouble
: http://ideone.com/HvfZb除了无损
float
->double
转换之外,没有进行任何转换。62.02
无法精确表示为 Cfloat
。当您float x=62.02
时,该变量将包含您提到的值。我强烈建议阅读每个计算机科学家应该了解的浮点运算知识。
Other than the lossless
float
->double
conversion, there is no conversion going on.62.02
cannot be represented exactly as a Cfloat
. The moment you dofloat 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.