Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
528 views
in Technique[技术] by (71.8m points)

python - 使用蒙特卡洛方法生成等边三角形(Generating an equilateral triangle using the Monte Carlo method)

I want to generate a triangle using the Monte Carlo method (In order to attribute a density that varies as a function of distance from the center to it) in a similar way to how this circle was generated to approximate pi.

(我想使用蒙特卡洛方法生成一个三角形(以便将密度作为从中心到它的距离的函数而变化),以类似于如何生成此圆以近似于pi的方式。)

import numpy as np
from numpy.random import random , seed 
import matplotlib.pyplot as plt
from datetime import datetime

startTime = datetime.now() #starts timing from now

N = int(1e6) #defines N

x,y=2*np.random.rand(2,N)-1 #define x and y as random numbers
r=np.sqrt(x*x+y*y) #defines radius
n=np.sum(r <= 1.0)
print(4*n/N) # approximate pi


inpond = np.sqrt(x**2+y**2) <= 1.0 # True if in the pond 

plt.figure()
plt.plot(x, y,'g.',label = 'grass', markersize = 1) #plot the non truth tested values
plt.plot(x[inpond==True], y[inpond==True],'b.',label = 'pond', markersize = 1) #plots truth tested values
plt.title('Pond generated using numpy.random') 
plt.xlabel('x')
plt.ylabel('y') #labeling

print(datetime.now() - startTime) #stops timer and prints

How would I go about doing so?

(我将如何去做?)

  ask by griston translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...