gpt4 book ai didi

python - 产生不同结果的等效 numpy 脚本

转载 作者:行者123 更新时间:2023-11-28 22:58:50 25 4
gpt4 key购买 nike

我运行了以下被认为相同的脚本,但输出完全不同,谁能解释为什么?

我首先导入了必要的模块:

from ctypes import *
import numpy as np

代码1:

AOVoltage = np.linspace(-1, 1, 2200)
AOVoltage = AOVoltage.ctypes.data_as(POINTER(c_double))
print AOVoltage.contents

c_double(1.821347161578237e-284)

代码2:

a = np.linspace(-1, 1, 2200)
AOVoltage = a.ctypes.data_as(POINTER(c_double))
print AOVoltage.contents

c_double(-1.0)

代码3:

AOVoltage = (np.linspace(-1, 1, 2200)).ctypes.data_as(POINTER(c_double))
print AOVoltage.contents

c_double(1.821347161578237e-284)

最佳答案

为此,您需要保留对原始 numpy 数组的引用,以防止它被垃圾回收。这就是 #2 有效而 #1 和 #3 无效的原因(它们的行为未定义)。

这在 documentation 中有解释:

Be careful using the ctypes attribute - especially on temporary arrays or arrays constructed on the fly. For example, calling (a+b).ctypes.data_as(ctypes.c_void_p) returns a pointer to memory that is invalid because the array created as (a+b) is deallocated before the next Python statement. You can avoid this problem using either c=a+b or ct=(a+b).ctypes. In the latter case, ct will hold a reference to the array until ct is deleted or re-assigned.

关于python - 产生不同结果的等效 numpy 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13476669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com