python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > python调用dll精度问题

python调用dll出现精度问题解决

作者:嘿,不许笑

本文主要介绍了python调用dll出现精度问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

问题:python 在调用dll 的时候出现了精度问题

总结:使用decimal库进行转换就可以正常传递。

遇到的问题具体情况

dll 生成函数代码声明如下

extern __declspec(dllexport) void LinearCompute(GoFloat64 currentX, GoFloat64 currentY, GoFloat64 targetX, GoFloat64 targetY, GoFloat64* resultX, GoFloat64* resultY);

使用python调用代码

from ctypes import *

# c_double 声明c 双精度小数变量
result_x = c_double(0)
result_y = c_double(0)

x_c = 1400.
y_c = 1450.
x_t = 1500.
y_t = 5600.

# byref 调用指针
dll.LinearCompute(c_double(x_c), c_double(y_c), c_double(x_t), c_double(y_t), byref(result_x), byref(result_y))

print(result_x.value, '  ', result_y.value)

但是输出的内容显示,输入到函数中的 x_c ,y_c 等数据对不上。

这里需要使用 decimal 库进行精度方面转换

所以以上代码改为如下:

from ctypes import *
from decimal import *

result_x = c_double(0)
result_y = c_double(0)

x_c = Decimal(1400)
y_c = Decimal(1450)

x_t = Decimal(1500)
y_t = Decimal(5600)

dll.LinearCompute(c_double(x_c), c_double(y_c), c_double(x_t), c_double(y_t), byref(result_x), byref(result_y))

print(result_x.value, '  ', result_y.value)

然后运行的结果如下

可以看见 传入的数值变得正常了。

附:https://www.jb51.net/article/275779.htm

Decimal类型的优点

Decimal类型是在浮点类型的基础上设计的,但是它在几个地方上要优于floating point:

比较重要的一点,如果使用 decimal 转换小数时,需要使用 单引号 引起来。

from decimal import *

print(Decimal(1.1) + Decimal(3.3))
print(Decimal(1.1) - Decimal(3.3))
print(Decimal(1.1) * Decimal(3.3))
print(Decimal(1.1) / Decimal(3.3))

#输出结果
'''
4.399999999999999911182158030
-2.199999999999999733546474090
3.630000000000000097699626167
0.3333333333333333781908292778
'''

但是如果使用字符串,就可以得到正常的结果了。

到此这篇关于python调用dll出现精度问题解决的文章就介绍到这了,更多相关python调用dll精度问题内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文