Fast numerical integration in Python

I have a program that has collected a certain integral many times and struggled to find a way to do it quickly. The integrals that I need to solve are as follows:

\ int ^ {b} _ {a (r)} f (x) * g (x-r) dx

I have to solve this integral for many different values ​​of r, which affects both the limits of integration and the integrand (through the function g). Because of this, I have not found a way to vectorize the problem and should instead rely on loops. This greatly slows down the problem, because I need to make function calls in every loop. Below is one way to do this using loops (using the data and functions made):

import numpy as np f = lambda x: x**2 g = lambda x: np.log(x) b=1000 r = np.arange(10,500,10) a = 1.1*r+r**-1 def loop1(r,a): integration_range=[np.linspace(a[i],b,1000) for i in range(len(a))] out=np.zeros(len(r)) i=0 while i<len(r): out[i]=np.trapz(f(integration_range[i])*a_pdf(integration_range[i]-r[i]),integration_range[i]) i=i+1 return out 

It takes about 17.7 ms, which is too slow for my current needs. I don’t care that the integrals are super accurate; I would be pleased with a solution that would give an approximation within 1% of the true value. Any help would be greatly appreciated!

+6
source share
1 answer

If you have a lot to do and f is more complex than your example, you can get some benefits from memoising f and possibly g.

What is memoization and how can I use it in Python?

Basically, anywhere you can cache computing and trading memory for the processor.

+3
source

Source: https://habr.com/ru/post/959101/


All Articles