Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/311.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 积分逼近_Python_Montecarlo - Fatal编程技术网

Python 积分逼近

Python 积分逼近,python,montecarlo,Python,Montecarlo,我看到了这个公式: 并尝试实现python算法来近似积分。它有点工作,但对我来说没有意义,所以如果有人能解释原因,那就好了:)这是我的代码: import random def monte_carlo(function, a, b, iter = 100000): """ function - 2d array of numbers, example: [[2, 1], [5, 4]] 2x^1 + 5x^4 a, b - boundaries Approxim

我看到了这个公式: 并尝试实现python算法来近似积分。它有点工作,但对我来说没有意义,所以如果有人能解释原因,那就好了:)这是我的代码:

import random

def monte_carlo(function, a, b, iter = 100000):
    """
    function - 2d array of numbers, example: [[2, 1], [5, 4]] 2x^1 + 5x^4
    a, b - boundaries
    Approximates integral
    """ 
    answer = 0
    for i in range(0, iter): 
        rpt = random.randrange(a, b+1)
        print(i , 'th ' , 'iteration')
        answer += evall(function, rpt) 

    return (1/(b-a))*answer
def evall(function, point):
    result = 0
    for term in function:
        result += term[0]*pow(point, term[1])
    return result


print('Answer is: ', monte_carlo([[1, 2]], 1, 100))
它是有效的。但是公式上说我们需要δX,所以如果我做:

deltaX = (b-a)/iter

然后将evall(function,rpt)乘以它,它应该也能工作,但不能。我使用的示例是函数x^2。

将您的
monte\u carlo
函数更改为:

def monte_carlo(function, a, b, iter = 100000):
    """
    function - 2d array of numbers, example: [[2, 1], [5, 4]] 2x^1 + 5x^4
    a, b - boundaries
    Approximates integral
    """ 
    answer = 0
    for i in range(0, iter): 
        rpt = random.random()*(b-a) + a  # Change to continuous uniform
        print(i , 'th ' , 'iteration')   # Probably don't want this
        answer += evall(function, rpt) 

    return (b-a)*answer/iter             # Corrects the Monte Carlo part

蒙特卡罗积分包括取平均值。您可能已经注意到,近似值会根据迭代次数而变化。随着迭代次数的增加,唯一应该改变的是蒙特卡罗错误。

…但它没有
-有什么问题吗?欢迎使用StackOverflow,而且。。。在这里申请。StackOverflow是针对特定编程问题的知识库,而不是教程资源。“向我解释这个代码”太宽泛了。向我们展示你对代码操作的跟踪,解释你理解的内容,以及你迷路的地方。我用[[1,2]]和边界100和1来称呼它,它是1和100之间的x^2积分,也就是333 333,你可以验证输出将远离NVM,我很愚蠢。。。我想起来了,谢谢。我能删除这篇帖子吗?谢谢,伙计!:)