Python 大数计算错误:为什么会发生这种情况?
我在repl.it中创建了一个小型Python程序来说明Collatz猜想,它说,如果从任何正整数n开始,递归地应用以下操作:n/2如果n是偶数,3n+1如果n是奇数,则始终会达到1 代码如下:Python 大数计算错误:为什么会发生这种情况?,python,Python,我在repl.it中创建了一个小型Python程序来说明Collatz猜想,它说,如果从任何正整数n开始,递归地应用以下操作:n/2如果n是偶数,3n+1如果n是奇数,则始终会达到1 代码如下: invalid_input = 0 while(invalid_input == 0): n = input("Give me a positive integer: ") try: #check for positive integer. If it cannot do int(n) it
invalid_input = 0
while(invalid_input == 0):
n = input("Give me a positive integer: ")
try: #check for positive integer. If it cannot do int(n) it means a string was entered, and it goes to except.
if(int(n)>0):
invalid_input = 1 #this is to tell the while loop above that the right input was entered
print("Thank you.")
print("Now loading:")
else: #an integer was entered, but it was negative
print("Please enter a positive integer")
except: #a string was entered
print("Please enter a positive integer")
n=int(n)
nentered = n #this will keep track of the initial n
npeak = n #this will keep track of the highest n reached
iteration = 1 #this will keep track of the number of iterations
iterationmax = 1 #this will keep tack of the iteration at which npeak was reached
while(n != 1):
print("%5i: %5i" % (iteration,n))
if(n % 2 == 0): #divide by 2 if even
n=n/2
else: #if it is odd, multiply by 3 and add 1
n=3*n+1
iteration = iteration + 1
if(n>npeak): #record the higher n and its iteration
npeak = n
iterationmax = iteration
它起作用了。但有一个问题:如果输入的数字足够大,例如666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666666。这就是我得到的:
Give me a positive integer: 6666666666666666666666666
Thank you.
Now loading:
1: 6666666666666666666666666
2: 3333333333333333277409280
3: 1666666666666666638704640
4: 833333333333333319352320
5: 416666666666666659676160
6: 208333333333333329838080
7: 104166666666666664919040
8: 52083333333333332459520
9: 26041666666666666229760
10: 13020833333333333114880
etc
正如你所看到的,我希望第二个数字正好是3333333,但是我在最后得到了不同的数字。
另一个例子是,输入10000000000000000000000在第二次迭代中返回4999999999991611392
原因可能是什么?将
/
操作更改为/
,以便它们不会导致(不准确的)浮点值
因此:
if(n % 2 == 0): #divide by 2 if even
n=n/2
应该是:
if(n % 2 == 0): #divide by 2 if even
n=n//2
或者按照Python约定正确格式化:
if n % 2 == 0:
n //= 2
将
/
操作更改为/
,以便它们不会导致(不准确的)浮点值
因此:
if(n % 2 == 0): #divide by 2 if even
n=n/2
应该是:
if(n % 2 == 0): #divide by 2 if even
n=n//2
或者按照Python约定正确格式化:
if n % 2 == 0:
n //= 2
@ruohola所说的之所以正确,是因为当您将浮点除法与单个
/
一起使用时,会产生一个浮点数。但是,由于数字太大,无法表示,因此会将其四舍五入到最接近的最精确表示。因此,您必须使用/
而不是/
但是,使用/
是整数除法。这将产生一个比高浮点更容易表示的整数
我们可以找到一个非常类似的问题,它包含了更多的解释。之所以@ruohola所说的是真的,是因为当你将浮点除法与单个
/
一起使用时,会产生一个浮点数。但是,由于数字太大,无法表示,因此会将其四舍五入到最接近的最精确表示。因此,您必须使用/
而不是/
但是,使用/
是整数除法。这将产生一个比高浮点更容易表示的整数
可以找到一个非常类似的问题,它包含了更多的解释。如果您使用的是Python 3.x,请注意
/
执行浮点除法。如果您使用的是Python 3.x,请注意/
执行浮点除法。非常感谢。我对你提到的最后一件事很感兴趣。因此,我可以通过写n+=1来实现n=n+1吗?@Luismi98是的!它们被称为复合运算符。你可以在这里读到更多,例如:非常感谢。我对你提到的最后一件事很感兴趣。因此,我可以通过写n+=1来实现n=n+1吗?@Luismi98是的!它们被称为复合运算符。您可以阅读以下内容,例如: