将 MATLAB 代码转换为 Python: Python 类型和操作顺序

Converting MATLAB code to Python: Python types and order of operations

这是 RainbowCrack 作者的 MATLAB 函数:

function ret = calc_success_probability(N, t, m)
arr = zeros(1, t - 1);
arr(1) = m;
for i = 2 : t - 1
    arr(i) = N * (1 - (1 - 1 / N) ^ arr(i - 1));
end

exp = 0;
for i = 1 : t - 1
    exp = exp + arr(i);
end

ret = 1 - (1 - 1 / N) ^ exp;

它计算在给定彩虹 table 和密钥空间 N、一个大的无符号整数、长度链 t 和链数的情况下找到明文密码的成功概率m.

样本运行:

calc_success_probability(80603140212, 2400, 40000000)

Returns 0.6055.

我很难将其转换为 Python。在 Python 3 中,不再有最大整数,因此 N 不是问题。我认为在计算中我必须将所有内容都强制为一个大的浮点数,但我不确定。

我也不知道MATLAB中的运算顺序。我认为代码是这样说的:

创建大小为 [1 .. 10] 的十个元素的数组 用零

初始化该数组的每个元素

在基于零的索引中,我认为这将是 array[0 .. t-1],看起来 MATLAB 使用 1 作为第一个(第 0 个)索引。

然后数组的第二个元素(从 0 开始的索引)初始化为 m

对于数组中的每个元素,pos=1(从 0 开始的索引)到 t-1:

array[pos] = N * (1 - (1 - 1/N) ** array[pos-1]

其中**是幂运算符。我觉得MATLAB中的幂是^,所以N * (1 - (1-1/N)array[pos-1]的幂就是上面那个

然后设置一个指数。对于数组 0 到 t-1 中的每个元素: 指数是指数 + 1

return 概率 = 1 - (1 - 1/N) exp 的幂;

我的 Python 代码看起来像这样,但不起作用。我不明白为什么,但可能是我对 MATLAB 不够了解,或者 Python,两者兼而有之,或者我以某种方式读错了数学,而 MATLAB 中发生的事情不是我的'我期待着,即我有操作顺序 and/or 类型错误以使其工作并且我在这些术语中遗漏了一些东西......

def calc_success_probability(N, t, m):

    comp_arr = []

    # array with indices 1 to t-1 in MATLAB, which is otherwise 0 to t-2???
    # range with 0, t is 0 to t excluding t, so t here is t-1, t-1 is up
    # to including t-2... sounds wrong...
    for i in range(0, t-1):
        # initialize array
        comp_arr.append(0)

    print("t = {0:d}, array size is {1:d}".format(t, len(comp_arr)))

    # zero'th element chain count
    comp_arr[0] = m

    for i in range(1, t-1):
        comp_arr[i] = N * (1 - (1 - 1 / N)) ** comp_arr[i-1]

    final_exp = 0
    for i in range(0, t-1):
        final_exp = final_exp + comp_arr[i]

    probability = (1 - (1 - 1 / N)) ** final_exp

    return probability

注意你的括号!您已经翻译了这个:

arr(i)      = N * (   1 - ( 1 - 1 / N )     ^  arr(i - 1)     );

对此:

comp_arr[i] = N * (   1 - ( 1 - 1 / N )   ) ** comp_arr[i-1]

我已经列出了所有内容,以便您可以更好地了解哪里出了问题。您将括号移到了错误的位置。

应该是:

comp_arr[i] = N * (   1 - ( 1 - 1 / N )     ** comp_arr[i-1]  )

同样,

ret = 1 - (1 - 1 / N) ^ exp;

不一样
probability = (1 - (1 - 1 / N)) ** final_exp

这应该是

probability = 1 - (1 - 1 / N) ** final_exp