Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing a function (Python)

I'm new to python and trying to do a HW assignment and it keeps throwing this error back at me (in iPython Notebook):

"TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'float'"

Here's the formula i'm trying to imitate: h(x)=(1/√2π)*e^−(1/2)^x^2

import numpy as np
import math
from math import *


def h_scalar(x):
    return (1 / sqrt(2 * pi)) * exp(-.50** x ** 2.00)

I'm trying to get the same out put as my teacher.

l = [-10.0, -1.0, 0.0, 1.0, 10.0] #
print h_scalar(l)
>>> [1.4867195147342977e-06, 0.24197072451914337, 0.3989422804014327,
0.24197072451914337, 1.4867195147342977e-06]

Here's the teachers question btw:

First of all, write a function called h_scalar. The function should expect a list (or in general an item that is iterable). It will expect that the list contains floating point values. It should return a new list of floats that are the h(x) for each x value in the input list. You should name your function h_scalar()

like image 703
user2839099 Avatar asked Oct 02 '13 14:10

user2839099


People also ask

What is vectorize function in Python?

What is Vectorization ? Vectorization is used to speed up the Python code without using loop. Using such a function can help in minimizing the running time of code efficiently.

What does it mean to vectorize a function?

Vectorization is the process of converting an algorithm from operating on a single value at a time to operating on a set of values (vector) at one time. Modern CPUs provide direct support for vector operations where a single instruction is applied to multiple data (SIMD).

What does vectorize do NumPy?

The vectorized function evaluates pyfunc over successive tuples of the input arrays like the python map function, except it uses the broadcasting rules of numpy. The data type of the output of vectorized is determined by calling the function with the first element of the input.

Is there Vectorization in Python?

Vectorization in Python, as implemented by NumPy, can give you faster operations by using fast, low-level code to operate on bulk data. And Pandas builds on NumPy to provide similarly fast functionality.


2 Answers

You will achieve a better performance using numpy's sqrt and exp, which will operate elementwise:

import numpy as np
from numpy import sqrt, exp, pi
def h_scalar(x):
    x = np.array(x)
    return (1/sqrt(2*pi)) * exp(-0.50*x**2)

You can use it like:

x = [-10.0, -1.0, 0.0, 1.0, 10.0]
h_scalar(x)
like image 92
Saullo G. P. Castro Avatar answered Sep 18 '22 22:09

Saullo G. P. Castro


If you want to use numpy.vectorize this is one option:

>>> import numpy as np
>>> h_scalar = np.vectorize(lambda x: (1 / np.sqrt(2 * np.pi)) * np.exp( -.50** x ** 2.00 ))
>>> l = np.array([-10.0, -1.0, 0.0, 1.0, 10.0])
>>> h_scalar(l)
like image 26
jabaldonedo Avatar answered Sep 18 '22 22:09

jabaldonedo