python turtle,random,math
# List imports here:
import turtle
import random
import math
# List constants here (NO MAGIC NUMBERS!):
NUMBER_DARTS = 1000
LEFT_BOUND = -2
RIGHT_BOUND = 2
TOP_BOUND = -2
BOTTOM_BOUND = 2
PEN_SIZE = 3
SQUARE_WIDTH = 2
SQUARE_TOP = 1
SQUARE_LEFT = -1
DOT_SIZE = 5
# Draws square given turtle, width and top left XY position
# param grapher (Turtle)
# param width (int)
# param topLeftX (int)
# param topLeftY (int)
def drawSquare( grapher, width, topLeftX, topLeftY ):
grapher.penup()
grapher.setpos(topLeftX, topLeftY)
grapher.setheading(0)
grapher.pendown()
grapher.forward(width)
grapher.right(90)
grapher.forward(width)
grapher.right(90)
grapher.forward(width)
grapher.right(90)
grapher.forward(width)
grapher.penup()
# Draws line given turtle and endpoints
# param grapher (Turtle)
# param xStart (int)
# param yStart (int)
# param xEnd (int)
# param yEnd (int)
def drawLine( grapher, xStart, yStart, xEnd, yEnd ):
grapher.penup()
grapher.setpos(xStart, yStart)
grapher.setheading(0)
angle_rad = math.atan2(yEnd - yStart, xEnd - xStart)
angle = angle_rad * 180.0 / math.pi
dist = math.sqrt((yEnd - yStart) * (yEnd - yStart) + (xEnd - xStart) * (xEnd - xStart))
grapher.pendown()
grapher.left(angle)
grapher.forward(dist)
grapher.penup()
# Draws a dot with given x, y coordinates
# param grapher (Turtle)
# param x (double)
# param y (double)
# param color (string)
def drawDot( grapher, x, y, color ):
#grapher.pencolor(color)
grapher.penup()
grapher.setpos(x, y)
grapher.dot(DOT_SIZE, color)
grapher.penup()
# Sets up 4X4 area with x- and y-axis to simulate dartboard
# param board - window that will simulate board
# param grapher - turtle that will do drawing
def setUpDartboard( board, grapher ):
# set up 4X4 area and set pensize
board.setworldcoordinates(LEFT_BOUND, TOP_BOUND, RIGHT_BOUND, BOTTOM_BOUND)
grapher.pensize(PEN_SIZE)
# Draw board
drawSquare( grapher, SQUARE_WIDTH, SQUARE_LEFT, SQUARE_TOP )
# Draw x- and y-axes
drawLine( grapher, LEFT_BOUND, 0, RIGHT_BOUND, 0 )
drawLine( grapher, 0, TOP_BOUND, 0, BOTTOM_BOUND )
# (Predicate Function)
# Determines whether or not dart falls inside unit circle with center at 0,0
# param dart (Turtle)
# return True if in circle, False if not
def inCircle( x, y ):
if x*x + y*y <= 1:
return True
else:
return False
# Algorithm for Monte Carlo simulation
# param numberDarts (int)
# param grapher (Turtle)
# return approximation of pi (float)
def montePi( numberDarts, grapher ):
# Initialize inCircleCount counter (THIS IS AN ACCUMULATOR)
inCircleCount = 0
# Loop for numberDarts
for i in range(0, numberDarts):
# Get random coordinate and position dart
x = random.random() * 2 - 1
y = random.random() * 2 - 1
# Draw red dot AND INCREMENT COUNTER if in circle, blue dot if not
if inCircle(x, y) == True:
inCircleCount = inCircleCount + 1
drawDot(grapher, x, y, "red")
else:
drawDot(grapher, x, y, "blue")
# return approximation of pi
return float(inCircleCount) / numberDarts * 4
#Performs Monte Carlo simulation to generate approximation of Pi
def main():
# Get number of darts for simulation from user
# Note continuation character <\> so we don't go over 78 columns:
print("This is a program that simulates throwing darts at a dartboard\n" \
"in order to approximate pi: The ratio of darts in a unit circle\n"\
"to the total number of darts in a 2X2 square should be\n"\
"approximately equal to pi/4")
#Create window, turtle, set up window as dartboard
window = turtle.Screen()
t = turtle.Turtle()
setUpDartboard(window, t)
PI = montePi( NUMBER_DARTS, t )
# Include the following code in order to update animation periodically
# instead of for each throw:
window.tracer(500)
#Conduct simulation and print result
print "Pi is approximately equal to " + str(PI)
#Keep the window up until dismissed
window.exitonclick()
main()
如图:
python turtle,random,math的更多相关文章
- 【转载】python 模块 - random生成随机数模块
随机数种子 要每次产生随机数相同就要设置种子,相同种子数的Random对象,相同次数生成的随机数字是完全相同的: random.seed(1) 这样random.randint(0,6, (4,5)) ...
- python使用random函数生成随机数
python使用random函数来生成随机数,常用的方法有: import random #生成0-1之间的数(不包括0和1) random.random() #生成1-5之间的随机整数(包括1和5) ...
- python+turtle 笔记
用Python+turtle绘制佩琪: from turtle import * def nose(x,y):#鼻子 penup()#提起笔 goto(x,y)#定位 pendown()#落笔,开始画 ...
- 从Scratch到Python——python turtle 一种比pygame更加简洁的实现
从Scratch到Python--python turtle 一种比pygame更加简洁的实现 现在很多学校都开设了Scratch课程,学生可以利用Scratch创作丰富的作品,然而Scratch之后 ...
- 让小乌龟可以唱歌——对Python turtle进行拓展
在Scratch中,小猫是可以唱歌的,而且Scratch的声音木块有着丰富的功能,在这方面Python turtle略有欠缺,今天我们就来完善一下. Python声音模块 Python处理声音的模块很 ...
- Python turtle绘制阴阳太极图代码解析
本文详细分析如何使用Python turtle绘制阴阳太极图,先来分解这个图形,图片中有四种颜色,每条曲线上的箭头表示乌龟移动的方向,首先从中心画一个半圆(红线),以红线所示圆的直径作半径画一个校园, ...
- 【转】python之random模块分析(一)
[转]python之random模块分析(一) random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): ...
- python的random()函数
python 的random函数需要调用 #!/usr/bin/python # -*- coding: UTF-8 -*- import random print( random.randint(1 ...
- Note of Python Turtle
Note of Python Turtle Turtle 库函数是 Python语言中一个流行的绘图函数库.Turtle 意思是海龟,在Python中显示为一个小箭头,通过它的移动而留 ...
随机推荐
- [OGRE]看备注学编程(02):打地鼠01-布置场地九只地鼠
项目下载地址:http://download.csdn.net/detail/wxg694175346/6340347 头文件ShrewMouseApplication.h: #ifndef __Sh ...
- UVALive 6525 Attacking rooks 二分匹配 经典题
题目链接:option=com_onlinejudge&Itemid=8&page=show_problem&problem=4536">点击打开链接 题意: ...
- poj 3181 Dollar Dayz (整数划分问题---递归+DP)
题目:http://poj.org/problem?id=3181 思路:将整数N划分为一系列正整数之和,最大不超过K.称为整数N的K划分. 递归:直接看代码: 动态规划:dp[i][j]:=将整数i ...
- [Angular 2] *ngFor with index
Let's see how to track index when we use 'ngFor: <li *ngFor="#hero of heros | async, #i = in ...
- C# WPF 建立渐隐窗口
需求: 一些无关紧要的提示信息,不显示出来怕用户一头雾水,但如果用对话框显示出来,用户又要动手把对话框关闭.不说别人,就是程序员自己测试时都觉得麻烦! 解决方案: 有两种选择 1. 选择是用 labe ...
- Android 基于Netty的消息推送方案之字符串的接收和发送(三)
在上一篇文章中<Android 基于Netty的消息推送方案之概念和工作原理(二)> ,我们介绍过一些关于Netty的概念和工作原理的内容,今天我们先来介绍一个叫做ChannelBuffe ...
- rpm包安装
RPM全称是“RedHatPackageManager”是由RedHat公司发发展起来的,本质是将软件源码包经过编译并且打包成rpm的格式,rpm文件包含的有二进制文件,配置文件,库文件等,同时RPM ...
- mybatis分页插件以及懒加载
1. 延迟加载 延迟加载的意义在于,虽然是关联查询,但不是及时将关联的数据查询出来,而且在需要的时候进行查询. 开启延迟加载: <setting name="lazyLoading ...
- 12 hdfs常用文件、目录拷贝操作、删除操作
package com.da.hbase.tool.utils; import com.da.hbase.tool.common.Const; import org.apache.hadoop.con ...
- 二维指针*(void **)的研究(uC/OS-II案例) 《转载》
uC/OS-II内存管理函数内最难理解的部分就是二维指针,本文以图文并茂的方式对二维指针进行了详细分析与讲解.看完本文,相信对C里面指针的概念又会有进一步的认识. 一.OSMemCreate( ) 函 ...