NumPy Incidence with Integration

I have a vector enter image description hereand want to make another vector of the same length whose kth component

enter image description here

Question: how can we vectorize this for speed? NumPy vectorize () is actually a for loop, so it doesn't count.

Veedrac noted that " It is not possible to apply a pure Python function to each element of a NumPy array without calling it many times ." Since I use NumPy functions and not "pure Python", I assume that this is possible for vectorization, but I do not know how to do this.

import numpy as np
from scipy.integrate import quad
ws = 2 * np.random.random(10) - 1
n  = len(ws)
integrals = np.empty(n)

def f(x, w):
    if w < 0: return np.abs(x * w)
    else:     return np.exp(x) * w

def temp(x): return np.array([f(x, w) for w in ws]).sum()

def integrand(x, w): return f(x, w) * np.log(temp(x))

## Python for loop
for k in range(n):
    integrals[k] = quad(integrand, -1, 1, args = ws[k])[0]

## NumPy vectorize
integrals = np.vectorize(quad)(integrand, -1, 1, args = ws)[0]

On a side note, is a Cython loop always faster than a NumPy vectorization?

+4
source share
2 answers

quad , , . .

for 10 . , , , , for.

( ), , . 2D NumPy, (a linspace). linspace, .

+9

@zaq's quad . .

fooobar.com/questions/1664173/... , vectorize , , . quad . , ws. x, , quad. quad integrand Python, numpy.

cython , C. , , quad. Cython .

, integrand ( ) cython, numpy .

def f(x, w):
    if w < 0: return np.abs(x * w)
    else:     return np.exp(x) * w

if w<0 w . , w? ,

 np.array([f(x, w) for w in ws]).sum()

 fn(x, ws).sum()

, x w , , math.exp .. np.exp. log abs.

f(x,w), x w, 2d. , temp integrand . quad x, , .

f(x,w) nx10 x=np.linspace(-1,1,n) ws, () .

+2

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


All Articles