Recall that random numbers can be used to compute the area or volume of a region
ID: 3699712 • Letter: R
Question
Recall that random numbers can be used to compute the area or volume of a region. This is done by picking many points at random and counting how many of them tall in the desired region, which can then be used to approximate the area For example, if we want to compute the area of a particular region that can be enclosed by a 2x2 square, we would choose random points within the 2x2 square and keep track of how many fall within our region of interest. If we find that half of the random points are contained within the region then the estimated area would be ×4=2. 1) Compute the volume enclosed by the function, z x4 y® by placing random points within a rectangular volume bounded by and 0 z 10. Use a large number of points and compare your estimated volume to the real volume of the integral. Vral 9.55. r O ?yExplanation / Answer
Ans 1.
import numpy as np
n = 100 #number of random values to generate
#generate random values for x, y, z
x = np.random.rand(n, )
y = np.random.rand(n, )
z = np.random.rand(n, ) * 10
c = 0 #count for the number of points within the curve
#check and update the count for points which lie within the curve
for i in range(n):
if (np.power(x[i], 4) + np.power(y[i], 3) + z[i] - 10 <= 0):
c+=1
real_vol = 9.55
approx_vol = float(c / n) * 10 #here 10 is the area of the rectangular region
print (approx_vol)
percent_error = float(np.abs(real_vol - approx_vol) / approx_vol) * 100
print (percent_error)
Follow up: Increase the value of n in steps of 100, you will get less than 1% relative error when generating around 400 random values.
Ans 2.
Note: Here, we assume the sphere to be inscribed in a cube of length 3 and hence generate points for x, y, z between [0, 3].
import numpy as np
#n is number of random values to generate
#generate random values for x, y, z for different values of n
for n in range(100, 100001, 10):
x = np.random.rand(n, ) * 3
y = np.random.rand(n, ) * 3
z = np.random.rand(n, ) * 3
c = 0 #count for the number of points within the circle
#check and update the count for points which lie within the circle
for i in range(n):
if (np.power(x[i], 2) + np.power(y[i], 2) + np.power(z[i], 2) - 9 <= 0):
c+=1
#print the approx or predicted volume and error
real_vol = (4 / 3) * np.pi * 27
approx_vol = float(c / n) * 27 #here 10 is the area of the rectangular region
print ("Approximate Volume: " ,approx_vol)
percent_error = float(np.abs(real_vol - approx_vol) / approx_vol) * 100
print ("Percentage Error: " ,percent_error)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.