Example #1
0
def swing_int(fun, x0, x1, blocks, points):
    """
    use monte carlo to integrate a wildy swinging function at endpoint
    # vähän kiire, tämä toimii ja käytetään nyt valmiita
    Parameters
    ----------
    fun : functipn
        function what to integrate
    x0 : double
        start point of integration
    x1 : double
        end point of integration
    blocks : int
        amount of blocks
    points : int
        how many points are calculated per block

    Returns
    -------
    double
        value of intergral

    """
    
    return monte_carlo_integration(fun, x0, x1, blocks, points)
def calculate_monte_carlo_errors():
    # Calculates numerical integral using monte carlo simulation
    # and compares the values to analytical answer
    correct_integral = 2
    errors = []
    iteration_amounts = np.linspace(40, 1000, 10, dtype=int)
    for iters in iteration_amounts:
        integral, dI = monte_carlo_integration(np.sin, 0., np.pi / 2, 10,
                                               iters)
        errors.append(2 * dI)  # 2SEM
    plot_monte_carlo_error(iteration_amounts, errors)
Example #3
0
def test_intKolmas():
    
    #wolfram alpha
    true = 6.647272079953789849569443469671631160297360492445608431
    blocks = np.arange(1,1000,100)    
    integral_errors = []
    
    for block in blocks:
        integral_errors.append(np.abs(monte_carlo_integration(kolmas, 0, 5, block, 1000)[0]- true))
        
    plt.plot(blocks*1000, integral_errors, 'ob', label = r'Int from 0 to 5 $f(x) = exp(sin(x^3)) $ ')
    plt.xlabel("number of points")
    plt.ylabel("Abs. error")    
    # plt.xlim(blocks[-1], blocks[0])
    plt.title("Integral error")    
    plt.xscale('log')
    plt.yscale('log')
    plt.legend(loc = 0)
    plt.show()
Example #4
0
from num_calculus import monte_carlo_integration

if __name__=="__main__":
        
    def fun(x):
        return  3*x**2 
    x = 0.8
    dx = 0.001
    
    der1 = test_first_derivative(fun, x, dx);
    print(der1)
    
    der2 = test_second_derivative(fun, x, dx);
    print(der2)    


    def fun2(x):
        return  np.sin(x)
    x0 = 0.9
    dx = np.pi/2
    n = 100    
    x2 = np.linspace(x0, dx, n)
    
    I_Riemann = Riemann_sum(fun2, x2, dx, n)
    
    I_trapezoid =  trapezoid_sum(fun2, x2, dx, n)
    
    I_Simpson = Simpson_sum(fun2, x2, dx, n)
    
    I, dI = monte_carlo_integration(fun2, 0.0, np.pi/2, 10, 100)
    print(I, '+/-', 2*dI)