0
2

More than 3 years have passed since last update.

CCC: coding crash course (4) 円周率3.141562.... に出現する数字をヒストグラムにする

Last updated at Posted at 2020-05-27

3.141562.... に出現する数字の頻度分布

円周率(PI)の小数点以下に出てくる数字のヒストグラムを作ります。

効率重視ではなく、初心者向けのやり方で試してみましょう。

まず、PIの小数点以下を http://www.eveandersson.com/pi/digits/pi-digits?n_decimals_to_display=500&breakpoint=500 で取得します。


char_pi = "14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912"

例えば、「0」の出現回数を調べるには:


count_0 = 0
for i in range(500):
    s = char_pi[i]
    if (s == "0"):
        count_0 = count_0 +1

print( count_0 )

同様にすれば、各数字が何回現れるのかを調べることができます。
最後に、グラフにして可視化します。


list_digits = [0,1,2,3,4,5,6,7,8,9,]

list_count = [0,0,0,0,0,0,0,0,0,0,]

for d in range(10):
    for i in range(500):
        s = char_pi[i]
        if (s == str(d)):
            list_count[d] = list_count[d] +1
    print(d, list_count[d])


from matplotlib import pyplot

pyplot.plot(list_digits, list_count, 'o')

pyplot.plot(list_digits, list_count, '-')

pyplot.ylim([0, max(list_count)+5])
pyplot.xlabel('Number')
pyplot.ylabel('Count')
pyplot.xticks([0,1,2,3,4,5,6,7,8,9,])

pyplot.show()

Figure_pi_digits_500.png

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2