gpt4 book ai didi

java - 从python到java的并行赋值变量(Pi算法)

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:22:55 33 4
gpt4 key购买 nike

我想将 python 算法转换为 Java,我有这个源代码(使用并行赋值变量(在 Java 中不存在 :( )

# -*- coding: cp1252 -*-
#! /usr/bin/env python

import sys



def main():
k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
while 1:
p, q, k = k*k, 2L*k+1L, k+1L
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
d, d1 = a/b, a1/b1
while d == d1:
output(d)
a, a1 = 10L*(a%b), 10L*(a1%b1)
d, d1 = a/b, a1/b1

def output(d):
sys.stdout.write(`int(d)`)
sys.stdout.flush()
#ecriture en continue du chiffre
pi = open("flypi.html", "a")
pi.write(`int(d)`)
pi.write("\n")
pi.close()


main()

所以,首先我重新编写了没有并行赋值变量的相同脚本:

# -*- coding: cp1252 -*-
#! /usr/bin/env python

import sys



def main():
#k, a, b, a1, b1 = 2L, 4L, 1L, 12L, 4L
k = 2L
a = 4L
b = 1L
a1 = 12L
b1 = 4L

while 1:

#p, q, k = k*k, 2L*k+1L, k+1L
kk = k
p = kk*kk
q = 2L*kk+1L
k = kk+1L

#a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
aa = a
bb = b
a = a1
b = b1
a1 = p*aa+q*a1
b1 = p*bb+q*b1

#d, d1 = a/b, a1/b1
d = a/b
d1 = a1/b1
while d == d1:
output(d)

#a, a1 = 10L*(a%b), 10L*(a1%b1)
a = 10L*(a%b)
a1 = 10L*(a1%b1)

#d, d1 = a/b, a1/b1
d = a/b
d1 = a1/b1

def output(d):
sys.stdout.write(`int(d)`)
sys.stdout.flush()
#ecriture en continue du chiffre
pi = open("flypi.html", "a")
pi.write(`int(d)`)
pi.write("\n")
pi.close()


main()

这两个脚本的输出是一样的:

31415926535897932384626433832795028841971693993751058209749445923078164062862089 (crt+c)

现在这是我用 Java 编写的脚本(几乎与第二个 python 脚本相同):

public static void cal(){
//int i = 0;
long d = 0;
long k = 2L;
long a = 4L;
long b = 1L, a1 = 12L, b1 = 4L;
long p = 0, q = 0, d1 = 0;

long aa = 0, bb = 0;
long kk = 0;


while(true){

kk = k;
p = kk*kk;
q = 2L*kk+1L;
k = kk+1L;

aa = a;
bb = b;
a = a1;
b = b1;
a1 = p*aa+q*a1;
b1 = p*bb+q*b1;

d = a/b;
d1 = a1/b1;
while(d == d1){
System.out.print(d);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
a = 10L*(a%b);
a1 = 10L*(a1%b1);

d = a/b;
d1 = a1/b1;
}
//i++;

}
}

但是输出是错误的:

31415926530000000001-100000000000000000100-300000101000000000000000000000000000000000000 (ctr+c)

谢谢,很抱歉发了这么长的帖子:)

编辑:所以是的,这是缓冲区溢出。我尝试实现 BigInteger 并且效果很好!谢谢!

最佳答案

在 Python 中整数可以是任意大的。在 Java 中,long 由 64 位组成,因此只能存储小于 2**64/2 的数字。

如果一个数字太大,它的前几位将被丢弃,最高有效位不是覆盖整数的符号,导致在数学上不可能的地方出现负数。

按照 ajb 的建议使用 BigInteger 或以某种方式更改您的计算。

关于java - 从python到java的并行赋值变量(Pi算法),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30688460/

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