【发布时间】:2015-08-21 16:45:54
【问题描述】:
我想将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 程序中的整数可以无限大吗? (我不知道 Python。)Java 中的long值有 2^63-1 的限制,如果计算超过该限制,它将回绕并可能产生负值。我不是说这就是问题所在。这只是我的第一个猜测。 -
具体来说,如果
b大于2^63/10,那么a%b可能会产生大于2^63/10 的结果,这意味着a = 10L*(a%b)将导致@ 987654331@ 否定。如果这似乎是问题所在,请考虑使用BigInteger而不是long。
标签: java python algorithm variable-assignment pi