代碼:
import matplotlib.pyplot as plt
import numpy as np
poslist = []
numlist = []
i = 1
num = int(input('Number to check?'))
plt.title(str(num) ': Collatz Graph')
plt.xlabel('Step')
plt.ylabel('Value')
print(num)
poslist.append(poslist, i)
numlist.append(numlist, num)
while True:
i = i 1
if num % 2 == 0:
num = num // 2
print(num)
elif num == 1:
break
else:
num = num * 3
num = num 1
print(num)
poslist.append(poslist, i)
numlist.append(numlist, num)
print('Number Array:', numlist)
print('Position Array', poslist)
plt.plot(*(poslist, numlist))
plt.show()
當我使用listname.append(listname, var)NumPy 函式時,它會跳過大部分變數。它只將每第 3 個或第 4 個變數添加到串列中。計步器陣列也是如此。即使在添加time.sleep(4)函式時,它似乎也一次計算 3 或 4 個數字 - 只記錄第一個。
uj5u.com熱心網友回復:
似乎有兩個問題。
- 您的
append命令是一個np.array,但poslist和numlist有list型。對于那些它只是numlist.append(num)和poslist.append(i)。而不是numpy.append您想要串列版本。 - 正如 diggusbickus 指出的那樣,while 回圈中的 append 陳述句位于 if 陳述句內,您需要將它們推回,以便它們在它之外。
import matplotlib.pyplot as plt
#import numpy as np <--- You are not using numpy
poslist = []
numlist = []
i = 1
num = int(input('Number to check?'))
plt.title(str(num) ': Collatz Graph')
plt.xlabel('Step')
plt.ylabel('Value')
print(num)
poslist.append(i) # <--- Change append statement for list
numlist.append(num) # <--- Same as above
while True:
i = i 1
if num % 2 == 0:
num = num // 2
print(num)
elif num == 1:
break
else:
num = num * 3
num = num 1
print(num)
poslist.append(i) # <--- Shift out of if/else statement and change append
numlist.append(num) # <--- Same as above
print('Number Array:', numlist)
print('Position Array', poslist)
plt.plot(*(poslist, numlist))
plt.show()
如果您想使用 numpy 陣列,另一個選項是更改您的串列。如果你想使用np.append,你會使用類似的東西poslist = np.append(poslist, i)。但是,正如 hpaulj 對此答案的評論中所建議的那樣,如果您想使用np.concatenate它,它看起來更像是poslist = np.concatenate((poslist, [i,])). (這篇文章比較了這兩種方法。)
import matplotlib.pyplot as plt
import numpy as np
poslist = np.array([]) # <--- change list to array
numlist = np.array([]) # <--- change list to array
i = 1
num = int(input('Number to check?'))
plt.title(str(num) ': Collatz Graph')
plt.xlabel('Step')
plt.ylabel('Value')
print(num)
#poslist = np.append(poslist, i) # <--- Fix syntax of np.append
poslist = np.concatenate((poslist, [i,])) # <-- Or use concatenate instead
numlist = np.concatenate((numlist, [num,])) # <-- Or use concatenate instead
while True:
i = i 1
if num % 2 == 0:
num = num // 2
print(num)
elif num == 1:
break
else:
num = num * 3
num = num 1
print(num)
poslist = np.concatenate((poslist, [i,])) # <--- Move out of if/else statement
numlist = np.concatenate((numlist, [num,]))
print('Number Array:', numlist)
print('Position Array', poslist)
plt.plot(*(poslist, numlist))
plt.show()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/350540.html
標籤:蟒蛇-3.x 麻木的 matplotlib 定时
