python - 蒙特卡洛高斯函数
问题描述
对于课堂作业,我需要执行以下操作(抱歉图片格式错误):
到目前为止,我有:
import math
def gaussian(x):
return ((1 / math.sqrt(2 * math.pi) * math.e) ** ( (-x ** 2) / 2))
# Problem 2.
def under_curve(x, y):
if 0 <= y <= gaussian(x):
return True
else:
return False
# Problem 3.
def greater_than(x, a):
if x > a:
return True
else:
return False
# Problem 4.
def less_than(x, b):
if x < b:
return True
else:
return False
# Problem 5.
def monte_carlo_gaussian(a, b, n):
import numpy as np
x = np.random.uniform(low=a, high=b, size=n)
y = np.random.uniform(low=a, high=b, size=n)
i = 0
ndartsunder = 0
ndarts = 0
for xi in x:
yi = y[i]
if less_than(x, b) is True:
ndartsunder = ndartsunder + 1 * under_curve(xi, yi)
ndarts += 1
i += 1
prob_under_curve = ndartsunder / ndarts
return b * prob_under_curve
我遇到的问题是monte_carlo_gaussian。我收到以下错误:
Traceback (most recent call last):
File "C:\Users\agsmi\Desktop\st114\homework7.py", line 104, in <module>
print(monte_carlo_gaussian(-1.644854, 1.644854, 10))
File "C:\Users\agsmi\Desktop\st114\homework7.py", line 92, in monte_carlo_gaussian
if less_than(x, b) is True:
File "C:\Users\agsmi\Desktop\st114\homework7.py", line 74, in less_than
if x < b:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
但我只是对如何整体设计这个功能感到非常困惑。任何帮助或提示让我朝着正确的方向前进将不胜感激。我想我也需要实现高斯函数,但我不确定如何/在哪里。感谢您的任何帮助。
解决方案
推荐阅读
- c - 搜索 -lczmq 时跳过不兼容的 czmq.lib,
- database - 实时环境中的数据迁移问题
- python - 生成随机数的归一化矩阵,其中行是从不同的高斯(正态)分布生成的
- php - 将关联数组展开 N 次并获取所有组合键
- python - Sklearn:ValueError:发现样本数量不一致的输入变量:[500, 1]
- swift - Searchfield 和 tableview - 仅显示具有大写用户名的用户
- node.js - Nodejs 生成一个密钥来签署一条数据
- python - 用于噪声过滤的图像上的 Python 奇异值分解
- mysql - MySQL 5.5 - 每天计算未清项目的条件
- c# - Premailer.Net error: Could not load type 'AngleSharp.Parser.Html.HtmlParser' from assembly AngleSharp 0.10.1