python - Recursive piecewise function in SymPy and summing over a list/array of coefficients -


for lack of latex editor, here picture of piecewise function wish plot using sympy. want pass in 2 arrays of coefficients , value x, evaluate , plot function. (edit : there 1 more p there alphas, image updated)

piecewise function attempt far (alpha , p lists/arrays, t number):

def getf(alpha,p,t):  #create argument list of tuples sympy.piecewise function argtuples = [] n,number in enumerate(alpha):     if n == 0:         argtuples.append((p[0]*x, x<alpha[0]))     elif 0<n , n<list(enumerate(alpha))[-1][0]:         argtuples.append((p[0]*alpha[0] + sum(p[i]*(alpha[i] - alpha[i-1]),(i,1,n)) + p[n+1]*(x-alpha[n]), alpha[n-1] <= x < alpha[n]))     else:         argtuples.append((p[0]*alpha[0] + sum(p[i]*(alpha[i] - alpha[i-1]),(i,1,n)) + p[n+1]*(x-alpha[n]), x>=alpha[n]))  f = piecewise(argtuples) return f(t)  sympy import piecewise, sum sympy.abc import x,  getf([10000,50000,100000,1000000],[0.05,0.08,0.15,0.30,0.40],1000001) 

however, i'm getting error "list indices must integers or slices, not symbol". how can reference coefficient values have passed function, given array length?

you cannot use symbolic index on python list (here i symbolic, since importing abc). if know list ahead of time, should use python sum function sum values, instead of sum.

sum(p[i]*(alpha[i] - alpha[i-1]) in range(1, n)) 

there problem, have alpha[n-1] <= x < alpha[n]. unfortunately won't work, due way python handles chained inequalities. have write and(alpha[n-1] <= 1, x < alpha[n]) otherwise typeerror: cannot determine truth value of relational.


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -