Question
Using python 3: You will create Python functions montePi and isInCircle to compute an approximation of using the Monte Carlo algorithm described in ch. 2.6
Using python 3: You will create Python functions montePi and isInCircle to compute an approximation of using the Monte Carlo algorithm described in ch. 2.6 of the text. Once you understand the Monte Carlo algorithm, review the code on p. 74. For this project, you will revise this code to include a docstring and to call a new function, isInCircle (which you will write), to determine whether the dart has hit the circle or not. The end result will be a cleaner, clearer look for montePi: by abstracting out the details of checking for the location of the dart, the montePi code will better reflect the underlying algorithm. montePi will have one parameter, numDarts, the number of times the approximating process should be run. montePi should return the approximate value for that is generated by the function. isInCircle, which will be called by montePi, will have three parameters, the x and y values of a point, and a radius, r. isInCircle should return True if the input point is inside the circle centered at point (0,0) with radius r, and False otherwise. isInCircle should return correct values for the simple examples included in your docstring, and also for the test cases given here.
>>> isInCircle(0, 0, 1)
True
>>> isInCircle(.5, .5, 1)
True
>>> isInCircle(1, 2, 1)
False
montePi should return approximate values for . Note that due to the randomness in the algorithm, approximations may vary slightly each time the function is executed. For example,
>>> montePi(100)
3.08 >>> montePi(100000)
3.143072
>>> montePi(10000000)
3.1418752
Finally, write a main function that calls (at least) these three example calls to montePi. Note that due to the randomness in the algorithm, approximations may vary slightly. Dont forget to print the results of the function calls, e.g., print(montePi(100)). The last line in your .py file should be a call to function main: main().
My code:
import random import math
def montePi(numDarts): isInCircle = 0 for i in range(numDarts): x = random.random() y = random.random() d = math.sqrt(x**2 + y**2) if d <= 1: isInCircle = isInCircle +1 pi = isInCircle / numDarts * 4 return pi
def isInCircle(x, y, r): r = 1 d = math.sqrt(x**2 + y**2) if d <= r: return True else: return False def main(): print(montePi(100)) print(montePi(1000)) print(montePi(10000)) print(montePi(100000)) main()
Does my code satisfy the requirements?
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started