#使用MonteCarlo模拟导入随机查找'e‘的值
FindE类:
def __init__(self):
self.s = 0
self.N = 1000000
def random_points(self):
for i in range(1,100000):
x = random.uniform(0, 1)
self.s += x
if self.s > 1.0:
return i
def exceed_dict(self, N):
d = dict()
for _ in range(N):
count = random_points()
if count not in d:
d[count] = 0
d[count] += 1
return d
def calculating_e(self):
d = exceed_dict(N)
print(sum([k*v for k, v in d.items()]) / N)E=打印()FindE(e.calculating_e())
发布于 2021-11-04 08:03:33
您正在尝试调用python类中的变量和方法。在调用self.之前,不要忘记使用它。应该是这样的:
import random
class FindE:
def __init__(self):
self.s = 0
self.N = 1000000
def random_points(self):
for i in range(1,100000):
x = random.uniform(0, 1)
self.s += x
if self.s > 1.0:
return i
def exceed_dict(self, N):
d = dict()
for _ in range(N):
count = self.random_points()
if count not in d:
d[count] = 0
d[count] += 1
return d
def calculating_e(self):
d = self.exceed_dict(self.N)
print(sum([k*v for k, v in d.items()]) / self.N)
e = FindE()
print(e.calculating_e())https://stackoverflow.com/questions/69835433
复制相似问题