我可以使用从头生成的随机数函数来预测 Pi(3.14) 的值吗?
Can I predict the value of Pi(3.14) using a random number function generated from scratch?
我尝试使用从头生成的随机函数来预测 Pi 的值。但它给出的输出是 4 而不是 3。14.My 用于预测 Pi 的代码在我使用“np.random.uniform”而不是我的随机 function.How 时可以完美地工作 我可以改进我的随机函数吗这样我就能得到 3.14 的输出?
import numpy as np
import matplotlib.pyplot as plt
#random function using linear congruent generator
def generate_rand(mult=16807,mod=(2**31)-1, seed=123456789, size=1):
U = np.zeros(size)
X = (seed*mult+1)%mod
U[0] = X/mod
for i in range(1, size):
X = (X*mult+1)%mod
U[i] = X/mod
return U
def generate_random(low=0,high=1, seed=123456789, size=1):
#Generates uniformly random number between 'low' and 'high' limits
return low+(high-low) *generate_rand(seed=seed, size=size)
def pi_estimator(samples):
points_inside_circle= 0
total_num_points = 0
for _ in range(samples):
x = generate_random()
y = generate_random()
distance = x**2 + y**2
if distance <= 1:
points_inside_circle +=1
total_num_points += 1
return 4* points_inside_circle/total_num_points
pi_estimator(10000)
问题是您的数字实际上并不是随机的。你要求一个随机数给出相同的“种子”,所以你总是得到相同的数字。
您需要让您的 generate_rand
成为 class 保存“种子”并使用最后一个数字作为“种子”,或者一次询问所有数字。我决定采用第二种方法
def pi_estimator(samples):
points_inside_circle= 0
total_num_points = 0
X,Y = generate_rand(size=2*samples).reshape(2,-1)
for x,y in zip(X,Y):
distance = x**2 + y**2
if distance <= 1:
points_inside_circle +=1
total_num_points += 1
return 4* points_inside_circle/total_num_points
现在 pi_estimator(10**7)
给出 3.1418544
对我来说看起来像 pi
。
我尝试使用从头生成的随机函数来预测 Pi 的值。但它给出的输出是 4 而不是 3。14.My 用于预测 Pi 的代码在我使用“np.random.uniform”而不是我的随机 function.How 时可以完美地工作 我可以改进我的随机函数吗这样我就能得到 3.14 的输出?
import numpy as np
import matplotlib.pyplot as plt
#random function using linear congruent generator
def generate_rand(mult=16807,mod=(2**31)-1, seed=123456789, size=1):
U = np.zeros(size)
X = (seed*mult+1)%mod
U[0] = X/mod
for i in range(1, size):
X = (X*mult+1)%mod
U[i] = X/mod
return U
def generate_random(low=0,high=1, seed=123456789, size=1):
#Generates uniformly random number between 'low' and 'high' limits
return low+(high-low) *generate_rand(seed=seed, size=size)
def pi_estimator(samples):
points_inside_circle= 0
total_num_points = 0
for _ in range(samples):
x = generate_random()
y = generate_random()
distance = x**2 + y**2
if distance <= 1:
points_inside_circle +=1
total_num_points += 1
return 4* points_inside_circle/total_num_points
pi_estimator(10000)
问题是您的数字实际上并不是随机的。你要求一个随机数给出相同的“种子”,所以你总是得到相同的数字。
您需要让您的 generate_rand
成为 class 保存“种子”并使用最后一个数字作为“种子”,或者一次询问所有数字。我决定采用第二种方法
def pi_estimator(samples):
points_inside_circle= 0
total_num_points = 0
X,Y = generate_rand(size=2*samples).reshape(2,-1)
for x,y in zip(X,Y):
distance = x**2 + y**2
if distance <= 1:
points_inside_circle +=1
total_num_points += 1
return 4* points_inside_circle/total_num_points
现在 pi_estimator(10**7)
给出 3.1418544
对我来说看起来像 pi
。