calc_pipy以下の説明に従ってPythonスクリプトを書け.1 +1~-1の一様乱数を発生させxに代入する.2 +1~-1の一様乱数を発生させyに代入する.※0~1の乱数は以下の手順で発生させることができる.import numpy as npnprandomrand3x yを2次元平面上の点の座標とするとその点の原点からの距離dは以下のように計算することができる.import mathd
import numpy as np
import math
N = 100000 # Number of iterations
cnt = 0 # Counter for points inside the circle
for _ in range(N):
x = np.random.uniform(-1, 1)
y = np.random.uniform(-1, 1)
d = math.sqrt(x**2 + y**2)
if d <= 1.0:
cnt += 1
p = cnt / N
pi = p * 4
print(pi)
このスクリプトでは、N回の繰り返しでランダムな点を生成し、その点が半径1の円内にあるかどうかを判定しています。最後に、円内にある点の割合から円周率を推定し、結果を表示します。
原文地址: https://www.cveoy.top/t/topic/jfEB 著作权归作者所有。请勿转载和采集!