简体   繁体   English

Monte-Carlo 方法的实现以找到 python 中的积分值

[英]Implementation of Monte-Carlo method to find integration value in python

I have found this code that can integrate a given function and give the answer using Monte-Carlo method.我发现这段代码可以集成给定的 function 并使用蒙特卡洛方法给出答案。 However, I wanted to implement it in python but I don't know how to make the "srand(time(Null))" and Rand_Max parts happen in python. Also I want to use the "func(x)" in such a way that I can input different function to get their integration value.但是,我想在 python 中实现它,但我不知道如何使“srand(time(Null))”和 Rand_Max 部分发生在 python 中。我还想在这样的情况下使用“func(x)”这样我就可以输入不同的 function 来获得它们的积分值。 Say I have a probability density function and I want to use this integration to find expectation value of x and x^2 to calculate variance of x (in this case, integration of x or x^2 times the probability density function).假设我有一个概率密度 function 并且我想使用这个积分来找到 x 和 x^2 的期望值来计算 x 的方差(在这种情况下,x 或 x^2 乘以概率密度函数的积分)。

#include<iostream>
#include<cmath>
#include<cstdlib>
#include<ctime>

using namespace std;

double func(double x)
{
 return (1+cos(x))*sin(abs(2*x))/abs(1+sin(2*x));
}

/*Common Monte Carlo method formula for integration*/

double MC_ID(double a, double b, double c, double d, int N)
{
 int i;
 double x, y, area;
 int count=0;
 for(i=0; i<=N; i++)
  {
    x=a+(b-a)*(rand()/(double)RAND_MAX);
    y=c+(d-c)*(rand()/(double)RAND_MAX);
    if(y<=func(x)) count++;
  area = (b-a)*(d-c)*((double)count/(double)N);
  }
return area;
}

int main()
{
 srand(time(NULL));
 cout<<MC_ID(M_PI,M_PI,-0.3,0.9,10000<<endl; 
return 0;
}

I want to implement it in python numpy library but I can't convert the seed and "srand(time(null))" and Rand-Max parts.我想在 python numpy 库中实现它,但我无法转换种子和“srand(time(null))”和 Rand-Max 部分。

import math
import random


def func(x):
    return (1+math.cos(x))*math.sin(abs(2*x))/abs(1+math.sin(2 *x)) #I want to make it (the "func(x)") so that I can input multiple equations to find its integration value or make the MC_ID a module to use it on another file?

def MC_ID(a, b, c, d, N):
    i = None
    x = None
    y = None
    area = None
    count = 0
    for i in range(0, N + 1):
        x = a+(b-a)*(random.random()/float(RAND_MAX)) #Problem***
        y = c+(d-c)*(random.random()/float(RAND_MAX)) #Problem***
        if y<=func(x):
            count += 1
            area = (b-a)*(d-c)*(float(count)/float(N))
        return area
#srand(time(None)) #Problem***
MC_ID(-math.pi, math.pi, -0.3, 0.9, 10000)
#This is my humble attempt.

I think there is no default RAND_MAX equivalent in python so we will add a function calculating it.我认为 python 中没有默认的RAND_MAX等效项,因此我们将添加一个 function 来计算它。

And for srand(time(None)) used in C++ it can be ignored in python.而C++中使用的srand(time(None))在python中可以忽略。

So let's try the following code:那么让我们试试下面的代码:

import math
import random


def func(x):
    return (1+math.cos(x))*math.sin(abs(2*x))/abs(1+math.sin(2 *x))

def RAND_MAX(size):
    """ Generates pseudo-numbers range and returns the max value
    Parameters
    ----------
    size : The length of random number list
    
    Returns
    -------
    Max of generated numbers
    """
    rands=[random.random() for i in range(size)]
    m=max(rands)
    
    return m
    
RAND_MAX=RAND_MAX(10000)

def MC_ID(a, b, c, d, N):
    i = None
    x = None
    y = None
    area = None
    count = 0
    for i in range(0, N + 1):
        x = a+(b-a)*(random.random()/float(RAND_MAX)) 
        y = c+(d-c)*(random.random()/float(RAND_MAX))
        if y<=func(x):
            count += 1
            area = (b-a)*(d-c)*(float(count)/float(N))
    return area

MC_ID = MC_ID(-math.pi, math.pi, -0.3, 0.9, 10000)

print(MC_ID)

Output Output

3.475858111931747
import math
import random
from sympy import *
import sympy


def main():
    expression = sympy.Symbol(input("Write the equation.. "))
    func(expression)
    a = float(input("Value of a:"))
    b = float(input("Value of b:"))
    c = float(input("Value of c:"))
    d = float(input("Value of d:"))
    N = int(input("Value of N:"))
    MC_ID_Value = MC_ID(a, b, c, d, N)
    print(f"Integrataion value: {MC_ID_Value}")


def func(expression):
    return expression


def RAND_MAX(size):
    """ Generates pseudo-numbers range and returns the max value
    Parameters
    ----------
    size : The length of random number list
    
    Returns
    -------
    Max of generated numbers
    """
    rands=[random.random() for i in range(size)]
    m=max(rands)
    
    return m
    
RAND_MAX=RAND_MAX(10000)

def MC_ID(a, b, c, d, N):
    i = None
    x = None
    y = None
    area = None
    count = 0
    for i in range(0, N + 1):
        x = a+(b-a)*(random.random()/float(RAND_MAX)) 
        y = c+(d-c)*(random.random()/float(RAND_MAX))
        if y<=func(x):
            count += 1
            area = (b-a)*(d-c)*(float(count)/float(N))
    return area


if __name__ == "__main__":
    main()

Will this work to input the equation via terminal input to find the expression turned into an equation for integration?这是否可以通过终端输入输入方程来找到转换为积分方程的表达式?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM