import random
import sympy
def estimate_pi_monte_carlo(Ntotal):
from nose.tools import assert_equal
import sympy
# Test that we return a float
assert_equal(type(estimate_pi_monte_carlo(100)),sympy.Rational)
from nose.tools import assert_almost_equal
import math
# Check that the correct value is output
# Correct approximations might be bad by chance so we put in an
error tolerance of 0.5
assert_almost_equal(estimate_pi_monte_carlo(100000),math.pi,delta=0.5)
from nose.tools import assert_raises
# Check that ValueError is raised on wrong input
assert_raises(ValueError,estimate_pi_monte_carlo,1.0)
from nose.tools import assert_raises
# Check that ValueError is raised on wrong input
assert_raises(ValueError,estimate_pi_monte_carlo,2.0)
from nose.tools import assert_almost_equal
import math
It is possible to use different methods to compute approximations to a. One way is to use a so-called Monte Carlo method which uses random numbers to estimate n. Consider the figure below, which shows the unit disc inscribed in the square (-1, 1] x [-1, 1]. Monte Carlo Approximation to n 1.0 10 0.5 0.5 0.0 0.0 -0.5 -0.5 -1.0 -1.0 -0.5 0.0 0.5 10 х -1.0 Pae -1.0 -0.5 0.0 0.5 10 Denote the areas of the square and disc A, and Ad, respectively. Then of course As = 4 and Ad = i So T Ad A 4 In the right-hand figure, a set of N total random points (uniformly distributed) have been plotted on the unit square. The points inside and outside the disc are coloured green and red, respectively. If the number of points inside the disc are denoted N disc , then the ratio of Ndisc to N total is an approximation of the ratio of areas above, namely N disc TT N disc >= 4 Ntotal 4 N total
(a) [4 marks] Write a function estimate_pi_monte_carlo which implements an algorithm for estimating a by generating a sequence of Ntotal uniformly distributed random numbers in the square [-1, 1] x [-1, 1], counting how many of those points land inside the unit circle, and then returning an approximation to a given by the formula above. The function should: • take the number 'Ntotal' as input and raise a ValueError if the input is not a positive integer; • return a rational number in the form of a sympy. Rational
import random import sympy def estimate_pi_monte_carlo(Ntotal): from nose.tools import assert_equal import sympy # Test
-
answerhappygod
- Site Admin
- Posts: 899604
- Joined: Mon Aug 02, 2021 8:13 am
import random import sympy def estimate_pi_monte_carlo(Ntotal): from nose.tools import assert_equal import sympy # Test
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!