Can Python do vectorized operations?

I want to implement the following Matlab code in Python:

x=1:100;
y=20*log10(x);

I tried using Numpy for this:

y = numpy.zeros(x.shape)
for i in range(len(x)):
    y[i] = 20*math.log10(x[i])

But for this, a for loop is used; Is there anyway to do a vector operation, as in Matlab? I know from some simple math, such as division and multiplication, this is possible. But what about other more complex operations, such as the logarithm here?

+1
source share
6 answers
y = numpy.log10(numpy.arange(1, 101)) * 20

In [30]: numpy.arange(1, 10)
Out[30]: array([1, 2, 3, 4, 5, 6, 7, 8, 9])

In [31]: numpy.log10(numpy.arange(1, 10))
Out[31]:
array([ 0.        ,  0.30103   ,  0.47712125,  0.60205999,  0.69897   ,
        0.77815125,  0.84509804,  0.90308999,  0.95424251])

In [32]: numpy.log10(numpy.arange(1, 10)) * 20
Out[32]:
array([  0.        ,   6.02059991,   9.54242509,  12.04119983,
        13.97940009,  15.56302501,  16.9019608 ,  18.06179974,  19.08485019])
+3
source

Yes of course.

x = numpy.arange(1, 100)
y = 20 * numpy.log10(x)
+3
source

Numpy , log10. numpy, , . C numpy , , Python.

:

y = 20*numpy.log10(x)
+2

- , , numpy, .

>>> import math
>>> x = range(1, 101)
>>> y = [ 20 * math.log10(z) for z in x ]
+1

numpy, , numpy.vectorize. :

    >>> def myfunc(a, b):
    ...     "Return a-b if a>b, otherwise return a+b"
    ...     if a > b:
    ...         return a - b
    ...     else:
    ...         return a + b
    >>>
    >>> vfunc = np.vectorize(myfunc)
    >>> vfunc([1, 2, 3, 4], 2)
    array([3, 4, 1, 2])
+1

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


All Articles