# 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的更多相关文章

  1. 【转载】python 模块 - random生成随机数模块

    随机数种子 要每次产生随机数相同就要设置种子,相同种子数的Random对象,相同次数生成的随机数字是完全相同的: random.seed(1) 这样random.randint(0,6, (4,5)) ...

  2. python使用random函数生成随机数

    python使用random函数来生成随机数,常用的方法有: import random #生成0-1之间的数(不包括0和1) random.random() #生成1-5之间的随机整数(包括1和5) ...

  3. python+turtle 笔记

    用Python+turtle绘制佩琪: from turtle import * def nose(x,y):#鼻子 penup()#提起笔 goto(x,y)#定位 pendown()#落笔,开始画 ...

  4. 从Scratch到Python——python turtle 一种比pygame更加简洁的实现

    从Scratch到Python--python turtle 一种比pygame更加简洁的实现 现在很多学校都开设了Scratch课程,学生可以利用Scratch创作丰富的作品,然而Scratch之后 ...

  5. 让小乌龟可以唱歌——对Python turtle进行拓展

    在Scratch中,小猫是可以唱歌的,而且Scratch的声音木块有着丰富的功能,在这方面Python turtle略有欠缺,今天我们就来完善一下. Python声音模块 Python处理声音的模块很 ...

  6. Python turtle绘制阴阳太极图代码解析

    本文详细分析如何使用Python turtle绘制阴阳太极图,先来分解这个图形,图片中有四种颜色,每条曲线上的箭头表示乌龟移动的方向,首先从中心画一个半圆(红线),以红线所示圆的直径作半径画一个校园, ...

  7. 【转】python之random模块分析(一)

    [转]python之random模块分析(一) random是python产生伪随机数的模块,随机种子默认为系统时钟.下面分析模块中的方法: 1.random.randint(start,stop): ...

  8. python的random()函数

    python 的random函数需要调用 #!/usr/bin/python # -*- coding: UTF-8 -*- import random print( random.randint(1 ...

  9. Note of Python Turtle

    Note of Python Turtle         Turtle 库函数是 Python语言中一个流行的绘图函数库.Turtle 意思是海龟,在Python中显示为一个小箭头,通过它的移动而留 ...

随机推荐

  1. jquery easyui Tab 引入页面的问题

    jQuery Easyui 的tabs插件有两种方式加载某个tab(标签页)上的内容:“href远程请求”和“content本地内容”,本文就两种方式的优缺点进行简单分析和思考. 两者特点: href ...

  2. Heritrix源码分析(十四)

    近段时间在搞定Lucene的一些问题,所以Heritrix源码分析暂时告一段落.今天下午在群里有同学提到了Heritrix异常终止的问题以及让Heritrix不停的抓取(就是抓完一遍后载入种子继续抓取 ...

  3. c++中基本的语法问题

    的输出是? 答案:构造函数的初始化列表 字符串转化为整形的代码: enum Status{ kValid = 0,kInvalid }; int g_nStatus = kValid; int Str ...

  4. SPOJ 416 - Divisibility by 15(贪心)

    糟烂的代码啊...  这个题目思路很简单——末位只可能为0和5,所有数字的和肯定被3整除 没有0和5的肯定不行 否则,把所有数字求和 如果被3整除,则从大到小输出 如果除3余1,则按以下顺序——删1: ...

  5. Unity 制作虚拟手柄例子

    Unity不愧是收费开发软件,有写好的Joystick(虚拟手柄),使用起来很简单,我们一起来学习一下哈!! 本文源代码Win版的 :http://vdisk.weibo.com/s/BDn59yfn ...

  6. 对return 语句的正确性和效率进行检查

    注意事项如下: 1. return 语句不可返回指向"堆栈内存“的”指针“或者”引用“,因为该内存单元在函数体结束时被自动释放. //错误 char* Func(void) { char s ...

  7. SELinux 与强制访问控制系统

    SELinux 全称 Security Enhanced Linux (安全强化 Linux),是 MAC (Mandatory Access Control,强制访问控制系统)的一个实现,目的在于明 ...

  8. Velocity 语法示例

    一.简介: 1)它允许任何人使用简单而强大的模板语言来引用定义在 java 代码中的对象" 2)Velocity是一个基于java的模板引擎,简称VTL(Velocity Template ...

  9. HTML 转文本及HTML内容提取(C#)

    //1.HTML直接转文本 //使用方法 HtmlToText convert = new HtmlToText(); textBox2.Text = convert.Convert(textBox1 ...

  10. [Mugeda HTML5技术教程之4] Studio 概述

    Mugeda Studio 是基于云平台的制作HTML5动画的专业可视化集成开发环境,可以让你在不需要安装客户端程序的情况下,只通过浏览器就能轻松创作高质量的HTML5动画.HTML5动画相对于传统的 ...