Vectorizing a function (Python)

user2839099 picture user2839099 · Oct 2, 2013 · Viewed 20.2k times · Source

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()

Answer

Saullo G. P. Castro picture Saullo G. P. Castro · Oct 2, 2013

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)