How to modify this Python define function code? -
could please take @ following function code in python?
import numpy np import scipy.stats stats scipy.stats import poisson, norm cs = 100 co = 300 mu = 4.7 g = poisson(mu) p = g.pmf(np.arange(3*mu)) # define z(q) function def z(q): in range(len(p)): return sum(p[i]*cs*max((q-i), 0) + p[i]*co*max((i-q), 0)) # plot q , (q) import pylab pl x = [] y = [] q in range(0, 12): x.append(q) y.append(z(q)) pl.plot(x, y, '-o') pl.show()
error message shows in last 'plot' procedure: in z(q), 'numpy.float64' object not iterable.
i z(q) returns value sum each in range (0, len(p)), function variable q. , plot q(x axis) , z(q)(y axis) each q can plotted.
how can modify z(q)? thank you!
and if output [q, z(q)] how make it? code:
open('opt.csv', 'wb') fd: = csv.writer(fd, delimiter=',') data1 = [['order_number', 'cost'], [q, z(q)]] a.writerows(data1)
if you're expecting z(q) return multiple values, may want use "yield" statement:
def z(q): in range(len(p)): yield sum(p[i]*cs*max((q-i), 0) + p[i]*co*max((i-q), 0))
this allow iterated on , return sum each run of loop.
if need ouput list rather generic iterable, you'll either need construct list in call, or wrap call z(q) in list: list(z(q))
edit:
after taking closer (and getting right libraries installed...), original answer seems incorrect. stack trace (which ideally included in question :) ) points return line in z itself. because original code trying run call sum
every time iterates on range(len(p))
rather running once on results.
you can adjust code correctly return single summed value moving sum outside function, ie:
import numpy np import scipy.stats stats scipy.stats import poisson, norm cs = 100 co = 300 mu = 4.7 g = poisson(mu) p = g.pmf(np.arange(3*mu)) # define z(q) function def z(q): in range(len(p)): yield p[i]*cs*max((q-i), 0) + p[i]*co*max((i-q), 0) # plot q , (q) import pylab pl x = [] y = [] q in range(0, 12): x.append(q) y.append(sum(z(q))) pl.plot(x, y, '-o') pl.show()
to summarise changes:
z(q)
yields each iteration of function described- the
sum
operation run on result ofz(q)
i hope helps!
Comments
Post a Comment