为什么函数从.so库返回随机值?

时间:2017-12-18 22:19:50

标签: python c

我在C上写了一个用于计算函数的小库。这是这个库的片段:

// Расчёт функции
struct function_value function(double x) {
        struct function_value result;
        result.argument = x;
        for (int i=1; 1; i++) {
                double element = pow(-1.0,i+1) * (pow(VAR*x,i+(i-1)) / fact(i+(i-1)));
                if (fabs(element) < EPSILON) break; 
                else result.value += element;
        }
        return result;
}

将此库绑定到小python程序:

from ctypes import *

libc = CDLL("../gmath/lib/gmathlib.so")


class FunctionValue(Structure):
    _fields_ = [("argument", c_double), ("value", c_double)]


arg = c_double(-2.0)
libc.function.restype = FunctionValue
print(libc.function(arg).value)
i = -2.0
while i <= 2.0:
    i += 0.25
    result = libc.function(c_double(i)).value
    print(result)

但程序有时会输出正确的函数值(图像1),有时会显示一个随机数(图像2)。为什么会这样?

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:6)

您从未初始化result.value,因此result.value += element;正在添加到未初始化的变量。

struct function_value function(double x) {
    struct function_value result;
    result.argument = x;
    result.value = 0;
    for (int i=1; 1; i++) {
        double element = pow(-1.0,i+1) * (pow(VAR*x,i+(i-1)) / fact(i+(i-1)));
        if (fabs(element) < EPSILON) break; 
        else result.value += element;
    }
    return result;
}