python 课件8.ppt

上传人:hyn****60 文档编号:70986921 上传时间:2023-01-31 格式:PPT 页数:79 大小:375.50KB
返回 下载 相关 举报
python 课件8.ppt_第1页
第1页 / 共79页
python 课件8.ppt_第2页
第2页 / 共79页
点击查看更多>>
资源描述

《python 课件8.ppt》由会员分享,可在线阅读,更多相关《python 课件8.ppt(79页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、 ProgrammingThinkingandMethod(8)ZhaoHai赵海赵海DepartmentofComputerScienceandEngineeringShanghaiJiaoTongU1Python Programming,1/eObjectivesTo understand the potential applications of simulation as a way to solve real-world problems.To understand pseudorandom numbers and their application in Monte Carlo s

2、imulations.To understand and be able to apply top-down and spiral design techniques in writing complex programs.2Python Programming,1/eObjectivesTo understand unit-testing and be able to apply this technique in the implementation and debugging of complex programming.3Python Programming,1/eSimulating

3、 RacquetballSimulation can solve real-world problems by modeling real-world processes to provide otherwise unobtainable information.Computer simulation is used to predict the weather,design aircraft,create special effects for movies,etc.4Python Programming,1/eA Simulation ProblemDenny Dibblebit ofte

4、n plays racquetball with players who are slightly better than he is.Denny usually loses his matches!Shouldnt players who are a little better win a little more often?Susan suggests that they write a simulation to see if slight differences in ability can cause such large differences in scores.5Python

5、Programming,1/eAnalysis and SpecificationRacquetball is played between two players using a racquet to hit a ball in a four-walled court.One player starts the game by putting the ball in motion serving.Players try to alternate hitting the ball to keep it in play,referred to as a rally.The rally ends

6、when one player fails to hit a legal shot.6Python Programming,1/eAnalysis and SpecificationThe player who misses the shot loses the rally.If the loser is the player who served,service passes to the other player.If the server wins the rally,a point is awarded.Players can only score points during thei

7、r own service.The first player to reach 15 points wins the game.7Python Programming,1/eAnalysis and SpecificationIn our simulation,the ability level of the players will be represented by the probability that the player wins the rally when he or she serves.Example:Players with a 0.60 probability win

8、a point on 60%of their serves.The program will prompt the user to enter the service probability for both players and then simulate multiple games of racquetball.The program will then print a summary of the results.8Python Programming,1/eAnalysis and SpecificationInput:The program prompts for and get

9、s the service probabilities of players A and B.The program then prompts for and gets the number of games to be simulated.9Python Programming,1/eAnalysis and SpecificationOutput:The program will provide a series of initial prompts such as the following:What is the probability player A wins a serve?Wh

10、at is the probability that player B wins a server?How many games to simulate?The program then prints out a nicely formatted report showing the number of games simulated and the number of wins and the winning percentage for each player.Games simulated:500Wins for A:268(53.6%)Wins for B:232(46.4%)10Py

11、thon Programming,1/eAnalysis and SpecificationNotes:All inputs are assumed to be legal numeric values,no error or validity checking is required.In each simulated game,player A serves first.11Python Programming,1/ePseudoRandom NumbersWhen we say that player A wins 50%of the time,that doesnt mean they

12、 win every other game.Rather,its more like a coin toss.Overall,half the time the coin will come up heads,the other half the time it will come up tails,but one coin toss does not effect the next(its possible to get 5 heads in a row).12Python Programming,1/ePseudoRandom NumbersMany simulations require

13、 events to occur with a certain likelihood.These sorts of simulations are called Monte Carlo simulations because the results depend on“chance”probabilities.The chaos program from chapter 1?The apparent randomness of the result came from repeatedly applying a function to generate a sequence of number

14、s.13Python Programming,1/ePseudoRandom NumbersA similar approach is used to generate random(technically pseudorandom)numbers.A pseudorandom number generator works by starting with a seed value.This value is given to a function to produce a“random”number.The next time a random number is required,the

15、current value is fed back into the function to produce a new number.14Python Programming,1/ePseudoRandom NumbersThis sequence of numbers appears to be random,but if you start the process over again with the same seed number,youll get the same sequence of“random”numbers.Python provides a library modu

16、le that contains a number of functions for working with pseudorandom numbers.15Python Programming,1/ePseudoRandom NumbersThese functions derive an initial seed value from the computers date and time when the module is loaded,so each time a program is run a different sequence of random numbers is pro

17、duced.The two functions of greatest interest are randrange and random.16Python Programming,1/ePseudoRandom NumbersThe randrange function is used to select a pseudorandom int from a given range.The syntax is similar to that of the range command.randrange(1,6)returns some number from 1,2,3,4,5 and ran

18、drange(5,105,5)returns a multiple of 5 between 5 and 100,inclusive.Ranges go up to,but dont include,the stopping value.17Python Programming,1/ePseudoRandom NumbersEach call to randrange generates a new pseudorandom int.from random import randrange randrange(1,6)5 randrange(1,6)3 randrange(1,6)2 rand

19、range(1,6)5 randrange(1,6)5 randrange(1,6)5 randrange(1,6)418Python Programming,1/ePseudoRandom NumbersThe value 5 comes up over half the time,demonstrating the probabilistic nature of random numbers.Over time,this function will produce a uniform distribution,which means that all values will appear

20、an approximately equal number of times.19Python Programming,1/ePseudoRandom NumbersThe random function is used to generate pseudorandom floating point values.It takes no parameters and returns values uniformly distributed between 0 and 1(including 0 but excluding 1).20Python Programming,1/ePseudoRan

21、dom Numbers from random import random random()0.79432800912898816 random()0.00049858619405451776 random()0.1341231400816878 random()0.98724554535361653 random()0.21429424175032197 random()0.23903583712127141 random()0.7291832884340891921Python Programming,1/ePseudoRandom NumbersThe racquetball simul

22、ation makes use of the random function to determine if a player has won a serve.Suppose a players service probability is 70%,or 0.70.if:score=score+1We need to insert a probabilistic function that will succeed 70%of the time.22Python Programming,1/ePseudoRandom NumbersSuppose we generate a random nu

23、mber between 0 and 1.Exactly 70%of the interval 0.1 is to the left of 0.7.So 70%of the time the random number will be 0.7,and it will be 0.7 the other 30%of the time.(The=goes on the upper end since the random number generator can produce a 0 but not a 1.)23Python Programming,1/ePseudoRandom Numbers

24、If prob represents the probability of winning the server,the condition random()prob will succeed with the correct probability.if random()scoreB:winsA=winsA+1 else:winsB=winsB+1 return winsA,winsB47Python Programming,1/eDesigning simNGames48Python Programming,1/eThird-Level DesignThe next function we

25、 need to write is simOneGame,where the logic of the racquetball rules lies.Players keep doing rallies until the game is over,which implies the use of an indefinite loop,since we dont know ahead of time how many rallies there will be before the game is over.49Python Programming,1/eThird-Level DesignW

26、e also need to keep track of the score and whos serving.The score will be two accumulators,so how do we keep track of whos serving?One approach is to use a string value that alternates between“A”or“B”.50Python Programming,1/eThird-Level DesignInitialize scores to 0Set serving to“A”Loop while game is

27、 not over:Simulate one serve of whichever player is serving update the status of the gameReturn scoresDef simOneGame(probA,probB):scoreA=0 scoreB=0 serving=“A”while:What will the condition be?Lets take the two scores and pass them to another function that returns True if the game is over,False if no

28、t.51Python Programming,1/eThird-Level Design52Python Programming,1/eThird-Level DesignAt this point,simOneGame looks like this:def simOneGame(probA,probB):#Simulates a single game or racquetball between players A and B#RETURNS As final score,Bs final score serving=A“scoreA=0 scoreB=0 while not gameO

29、ver(scoreA,scoreB):53Python Programming,1/eThird-Level DesignInside the loop,we need to do a single serve.Well compare a random number to the provided probability to determine if the server wins the point(random()prob).The probability we use is determined by whom is serving,contained in the variable

30、 serving.54Python Programming,1/eThird-Level DesignIf A is serving,then we use As probability,and based on the result of the serve,either update As score or change the service to B.if serving=A:if random()probA:scoreA=scoreA+1 else:serving=B55Python Programming,1/eThird-Level DesignLikewise,if its B

31、s serve,well do the same thing with a mirror image of the code.if serving=A:if random()probA:scoreA=scoreA+1 else:serving=B“else:if random()probB:scoreB=scoreB+1 else:serving=A56Python Programming,1/eThird-Level DesignPutting the function together:def simOneGame(probA,probB):#Simulates a single game

32、 or racquetball between players A and B#RETURNS As final score,Bs final score serving=A scoreA=0 scoreB=0 while not gameOver(scoreA,scoreB):if serving=A:if random()probA:scoreA=scoreA+1 else:serving=B else:if random()import rball rball.gameOver(0,0)False rball.gameOver(5,10)False rball.gameOver(15,3

33、)True rball.gameOver(3,15)True64Python Programming,1/eUnit TestingNotice that weve tested gameOver for all the important cases.We gave it 0,0 as inputs to simulate the first time the function will be called.The second test is in the middle of the game,and the function correctly reports that the game

34、 is not yet over.The last two cases test to see what is reported when either player has won.65Python Programming,1/eUnit TestingNow that we see that gameOver is working,we can go on to simOneGame.simOneGame(.5,.5)(11,15)simOneGame(.5,.5)(13,15)simOneGame(.3,.3)(11,15)simOneGame(.3,.3)(15,4)simOneGam

35、e(.4,.9)(2,15)simOneGame(.4,.9)(1,15)simOneGame(.9,.4)(15,0)simOneGame(.9,.4)(15,0)simOneGame(.4,.6)(10,15)simOneGame(.4,.6)(9,15)66Python Programming,1/eUnit TestingWhen the probabilities are equal,the scores arent that far apart.When the probabilities are farther apart,the game is a rout.Testing e

36、ach component in this manner is called unit testing.Testing each function independently makes it easier to spot errors,and should make testing the entire program go more smoothly.67Python Programming,1/eSimulation ResultsIs it the nature of racquetball that small differences in ability lead to large

37、 differences in final score?Suppose Denny wins about 60%of his serves and his opponent is 5%better.How often should Denny win?Lets do a sample run where Dennys opponent serves first.68Python Programming,1/eSimulation ResultsThis program simulates a game of racquetball between twoplayers called A and

38、 B.The abilities of each player isindicated by a probability(a number between 0 and 1)thatthe player wins the point when serving.Player A alwayshas the first serve.What is the prob.player A wins a serve?.65What is the prob.player B wins a serve?.6How many games to simulate?5000Games simulated:5000Wi

39、ns for A:3329(66.6%)Wins for B:1671(33.4%)With this small difference in ability,Denny will win only 1 in 3 games!69Python Programming,1/eOther Design TechniquesTop-down design is not the only way to create a program!70Python Programming,1/ePrototyping andSpiral DevelopmentAnother approach to program

40、 development is to start with a simple version of a program,and then gradually add features until it meets the full specification.This initial stripped-down version is called a prototype.71Python Programming,1/ePrototyping andSpiral DevelopmentPrototyping often leads to a spiral development process.

41、Rather than taking the entire problem and proceeding through specification,design,implementation,and testing,we first design,implement,and test a prototype.We take many mini-cycles through the development process as the prototype is incrementally expanded into the final program.72Python Programming,

42、1/ePrototyping andSpiral DevelopmentHow could the racquetball simulation been done using spiral development?Write a prototype where you assume theres a 50-50 chance of winning any given point,playing 30 rallies.Add on to the prototype in stages,including awarding of points,change of service,differin

43、g probabilities,etc.73Python Programming,1/ePrototyping andSpiral Developmentfrom random import randomdef simOneGame():scoreA=0 scoreB=0 serving=A for i in range(30):if serving=A:if random().5:scoreA=scoreA+1 else:serving=B else:if random()simOneGame()0 00 10 12 72 82 83 83 83 83 83 83 83 93 94 95 9

44、74Python Programming,1/ePrototyping andSpiral DevelopmentThe program could be enhanced in phases:Phase 1:Initial prototype.Play 30 rallies where the server always has a 50%chance of winning.Print out the scores after each server.Phase 2:Add two parameters to represent different probabilities for the

45、 two players.75Python Programming,1/ePrototyping andSpiral DevelopmentPhase 3:Play the game until one of the players reaches 15 points.At this point,we have a working simulation of a single game.Phase 4:Expand to play multiple games.The output is the count of games won by each player.Phase 5:Build t

46、he complete program.Add interactive inputs and a nicely formatted report of the results.76Python Programming,1/ePrototyping andSpiral DevelopmentSpiral development is useful when dealing with new or unfamiliar features or technology.If top-down design isnt working for you,try some spiral development

47、!77Python Programming,1/eThe Art of DesignSpiral development is not an alternative to top-down design as much as a complement to it when designing the prototype youll still be using top-down techniques.Good design is as much creative process as science,and as such,there are no hard and fast rules.78Python Programming,1/eThe Art of DesignThe best advice?Practice,practice,practice79Python Programming,1/e

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 生活休闲 > 生活常识

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁