2017-10-10 89 views
0

嘗試使用sqrt方法生成bin大小的直方圖。我究竟做錯了什麼?我的代碼如下給我錯誤。謝謝。Python中使用sqrt方法選擇bin大小的直方圖

TypeError: 'float' object cannot be interpreted as an integer

values = [1,5,2,8,5,11,24,30,50] 
x = len(values) 
binsizes = math.sqrt(x) 
plt.hist(values, bins = binsizes) 
plt.show() 
+1

它是否給出了特別的錯誤?對於任何特定的行? –

回答

1

math.sqrt(x)返回一個浮點數。箱arg期待一個整數。你需要投binsizes在一些點INT:

values = [1,5,2,8,5,11,24,30,50] 
x = len(values) 
binsizes = math.sqrt(x) 
plt.hist(values, bins = int(binsizes)) 
plt.show() 
1

在這裏,你需要讓你的math.sqrt爲int,如果不作出詮釋,你總是會收到一條錯誤

n = np.zeros(bins, ntype) TypeError: 'float' object cannot be interpreted as an integer In your code binsizes is float type and hence need to be converted to int

import math 
import numpy as np 
import matplotlib.pyplot as plt 
values = [1,5,2,8,5,11,24,30,50] 
x = len(values) 
print(x) 
binsizes = int(math.sqrt(x)) 
plt.hist(values, bins = binsizes) 
plt.show()