首页 > 解决方案 > 蒙特卡洛高斯函数

问题描述

对于课堂作业,我需要执行以下操作(抱歉图片格式错误):

在此处输入图像描述

到目前为止,我有:

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()

但我只是对如何整体设计这个功能感到非常困惑。任何帮助或提示让我朝着正确的方向前进将不胜感激。我想我也需要实现高斯函数,但我不确定如何/在哪里。感谢您的任何帮助。

标签: pythonfunctionloops

解决方案


推荐阅读