大数计算错误:为什么会发生这种情况?

2024-04-25 01:44:02 发布

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

我创建了一个小的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 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在第二次迭代中返回49999999999191611392。你知道吗

为什么会这样?你知道吗


Tags: oftheinputifitintegerthiswill
2条回答

@ruohola所说的之所以是真的,是因为当您使用带有单个/的浮点除法时,会产生一个浮点数。但是,由于数字太大,因此无法表示,因此将其四舍五入到最接近最精确的表示形式。因此您必须使用//而不是/。你知道吗

但是,使用//是整数除法。这将产生一个整数,它可以比高浮点更容易表示。你知道吗

一个非常相似的问题可以在here中找到,它包含了更多的解释。你知道吗

/操作更改为//,这样它们就不会产生(不准确的)浮点值。你知道吗

因此:

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

相关问题 更多 >