python - np.piecewise() acting up with use of math.pow()? -
i've been trying numpy.piecewise convert list of coefficients {a_ij} piecewise cubic polynomial. whenever run following code,
import math import numpy np x = np.linspace(0.1,9.9,100) = [[i] * 4 in range(10)] x_i = [0,1,2,3,4,5,6,7,8,9,10] condlist = [(x[i] < x)*(x<x_i[i+1]) in range(len(x_i)-1)] funclist = [lambda y: sum([a[k][j] * math.pow(y - x_i[k],j) j in range(4)]) k in range(len(a))] print np.piecewise(x, condlist, funclist)
i error
...line 730, in piecewise y[condlist[k]] = item(vals, *args, **kw) file "test", line 8, in <lambda> funclist = [lambda y: sum([a[k][j] * math.pow(y - x_i[k],j) j in range(4)]) k in range(len(a))] typeerror: length-1 arrays can converted python scalars
the error goes away, however, if , if rid of math.pow(). reason, having funclist pass x math.pow() breaks everything.
what's going on? how can fix this?
the functions in math
module expect numeric scalars arguments. don't expect numpy arrays. functions in funclist
being passed numpy array, y
. math.pow(y-constant, j)
raising typeerror:
in [22]: y = np.arange(5) in [31]: math.pow(y - 1, 2) typeerror: length-1 arrays can converted python scalars
use np.power
instead of math.pow
:
funclist = [lambda y: ([a[k][j] * np.power(y - x_i[k],j) j in range(4)]).sum() k in range(len(a))]
note: instead of using python sum
function, should call numpy sum
method better performance.
Comments
Post a Comment