I was trying to generate random points and keep the ones that were inside the curve, and it's getting a bit difficult. Here's my code:
import numpy as np
import matplotlib.pyplot as plt
N=eval(input("Enter the number of points used for integration:"))
a,b=eval(input("Enter the range of integration:"))
def f(x):
return x/(x**2 + 1)
x=np.random.uniform(a,b,N)
y=np.random.uniform(a,b,N)
a=np.linspace(a,b,N)
A=[f(j) for j in x]
xx=x.tolist()
yy=y.tolist()
xx.sort()
yy.sort()
X=[]
Y=[]
for i in range(N):
if yy[i]<A[i]:
Y.append(yy[i])
X.append(xx[i])
plt.plot(a,f(a),color='black',label="given function")
plt.grid()
plt.scatter(X,Y)
plt.legend()
plt.show()
But what I keep getting is just a distribution across the entire grid where I have specifically used if inside the for loop to mention my condition. What's going on?
I was trying to generate random numbers and them keep the ones that were under the curve. What I expected was exactly that. I tried to sort the lists of random numbers using sort() but that somehow makes it worse.
You can try this way:
def f(x):
return x/(x**2 + 1)
x=np.random.uniform(a,b,N)
y=np.random.uniform(0,1,N)
a=np.linspace(a,b,N)
A=[f(j) for j in x]
xx=x.tolist()
yy=y.tolist()
# xx.sort()
# yy.sort()
X=[]
Y=[]
for i in range(N):
if yy[i]<A[i]:
Y.append(yy[i])
X.append(xx[i])
plt.plot(a,f(a),color='black',label="given function")
plt.grid()
plt.scatter(X,Y)
plt.legend()
plt.show()
The problem with original code in question was that values of y
were being chosen in the range a to b given by the following line.
y=np.random.uniform(a,b,N)
Since all the values of y
were greater than values generated by function f
, nothing falls under the curve in the original code given in question. The values should be chosen between 0-1 as the function divides the each element of x
by x**2+1
. So each value of y should be a decimal lying between 0 to 1.
Also we dont need to sort the values.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.