2019/5/12 Pythonハンズオン サンプルプログラム

Hello World!プログラム

print("Hello World!")

数値微分を求める

def f(x):
  y = x ** 2
  return y

def diff(x, h):
  d = ( f(x+h) - f(x) ) / h
  return d

h = 10e-5 # h は0に限りなく近い極限。ここでは 10 の -5 乗。

for x in range(10):
  print("関数 y = x ** 2 における x = ", x, " の時の傾きは", diff(x,h) )

モンテカルロ法を利用して円周率を求める

import matplotlib.pyplot as plt
import random
import math

iterator = 3000 # 点を打つ数

cnt = 0
for i in range(iterator):
  # x, y に1~100の乱数をセットする
  x = random.randint(1, 100)
  y = random.randint(1, 100)
  d = math.sqrt((x-50)**2 + (y-50)**2) # 円の中心を50, 50として、その中心から点までの距離を三平方の定理を使って求める。
  if (d <= 50): # 距離が半径以内つまり50以内の場合の処理
    cnt += 1
    plt.scatter(x, y, marker='.', c='r') # 赤色の点を描画
  else: # 距離が半径より大きい場合の処理
    plt.scatter(x, y, marker='.', c='g') # 緑色の点の描画
    
plt.axis('equal') # 現在表示している座標の最大・最小を[xmin, xmax, ymin, ymax]の形式で返す。
plt.show()

# 円周率を求める
p = cnt / iterator
pi = p * 4
print(pi)

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です