Integral Monte Carlo

  integral, montecarlo, python-3.x

He tried to calculate the integral of monteCarlo. I fill the values with numpy in the input, but if I try to put log or some number like 10 ** 2 I get an error, any idea what I can do? Here is my code

import numpy as np
from sympy import Symbol

def main() :
    x = Symbol('x')
    def func(x):
        func=eval(fun)
        return func
    fun = input('Funcion: ')
    a = int(input("Limite inferior : "))
    b = np.pi
    N = int(input("Intervalos : "))
    q = 0
    i = 0
    x = np.linspace(a,b,N)
    fmin = min(func(x))
    fmax = max(func(x))
    area = (b-a)*(fmax-fmin)
    xrand = np.random.uniform(a,b,N)
    yrand = np.random.uniform(fmin,fmax,N)

    while(i <=  N):
        if(yrand[i-1] <= func(xrand[i-1])):
            q += 1
            if(i == N):
                break
            else :
                i += 1
        else :
            if(i == N):
                break
            else :
                i += 1

    print("Numeros aleatorios ",q)
    valorIntegral  = (np.sum(q)/N)*area
    print("Valor : ",valorIntegral)
main()

Source: Python-3x Questions

LEAVE A COMMENT