尝试在Python中复制小型C代码

2024-06-11 20:58:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python复制一些C代码。你知道吗

这是C代码。你知道吗

#include <math.h>
double AttackerSuccessProbability(double q, int z)
{
 double p = 1.0 - q;
 double lambda = z * (q / p);
 double sum = 1.0;
 int i, k;
 for (k = 0; k <= z; k++)
 {
  double poisson = exp(-lambda);
  for (i = 1; i <= k; i++)
    poisson *= lambda / i;
    sum -= poisson * (1 - pow(q / p, z - k));
 }
 return sum;
}

C代码只是对这个等式进行建模,取自Bitcoin's whitepaperPoission probablity

下面是我在python中的尝试。你知道吗

def BitcoinAttackerSuccessProbablity(q, z):
    # probablity of honest finding the next node is 1 - probablity the attacker will find the next
    p = 1 - q
    # lambda is equal to the number of blocks times by the division of attacker and honest finding the next block
    lam = z * (q / p)
    sum = 1.0
    i = 1
    k = 0

    while k <= z:
        poisson = math.exp(-1 * lam)
        while i <= k:
            poisson = poisson * (lam / i)
            i = i + 1
        sum = sum - (poisson * (1 - ((q / p) ** (z - k))))
        k = k + 1

    print(sum)


for x in range(0,11):
    BitcoinAttackerSuccessProbablity(0.1, x)

C代码的结果是。(q和z是输入,P是输出。)

q=0.1    

z=0 P=1.0000000
z=1 P=0.2045873
z=2 P=0.0509779
z=3 P=0.0131722
z=4 P=0.0034552
z=5 P=0.0009137
z=6 P=0.0002428
z=7 P=0.0000647
z=8 P=0.0000173
z=9 P=0.0000046
z=10 P=0.0000012

我试图通过转换C代码在python中准确地复制这些结果。我的前3个结果(z=0,-3)是正确的,但是其余的结果是不正确的。当我将while循环改为C中的等价循环时,只有前两个结果是正确的。你知道吗

Python代码的结果

1.0
0.20458727394278242
0.05097789283933862
-0.057596282822218514
-0.1508215598462347
-0.22737700216279746
-0.28610012088884856
-0.3272432217416562
-0.3519591169464781
-0.36186779773540745
-0.35878211836275675

我认为在语言之间如何处理循环很简单。你知道吗

任何帮助都将不胜感激

编辑:

这是第一次尝试

def BitcoinAttackerSuccessProbablity(q, z):
# probablity of honest finding the next node is 1 - probablity the attacker will find the next
p = 1 - q
#lambda is equal to the number of blocks times by the division of attacker and honest finding the next block
lam = z * (q/p)
sum = 1.0


for k in range(0, z):
    poisson = math.exp(-1*lam)
    for i in range(1, k):
        poisson = poisson * (lam/i)
    sum = sum - (poisson * (1 - ((q/p)**(z-k))))

print(sum)

Tags: ofthelambda代码forisnextpoisson
1条回答
网友
1楼 · 发布于 2024-06-11 20:58:13

while i <= k循环之前,不能将i重新初始化为零。你知道吗

更地道的(而且要短得多!)用Python编写这个函数的方法是使用带有sum()函数的generator expression来执行求和,以及使用math.factorial()函数来代替循环中的阶乘计算。使用这种方法,代码变成了原始数学公式的直接翻译:

def BitcoinAttackerSuccessProbablity(q, z):
    # probablity of honest finding the next node is 1 - probablity the attacker
    # will find the next
    p = 1 - q
    # lambda is equal to the number of blocks times by the division of attacker
    # and honest finding the next block
    lam = z * (q / p)

    return 1 - sum(
            (lam ** k) * math.exp(-lam) / math.factorial(k)
            * (1 - (q / p) ** (z - k))
            for k in range(0, z+1)
            )

注意,范围被设置为range(0, z+1),而不是range(0, z),因为Python范围不包括stop值。你知道吗

相关问题 更多 >