-2

I am trying to find parameters A,B,C to data x,y using model y= Ax^2 sin(x)/cos(x)^C + B I want to use leastsq from scipy.optimize but I've got error. Here is my attempt:

x=n.array(x)
y=n.array(y)

model=lambda tpl,x :(tpl[0]*x**2 * n.sin(x))/((n.cos(x)**tpl[2]) *tpl[1])
func=model
err=lambda tpl,x,y: func(tpl,x)-y
init=(3.0,8.0,4.0)
param=scipy.optimize.leastsq(err,init[:],args=(x,y))
print(param[o])

Where init are my "first guess" of parameters A,B,C

Error:

Warning (from warnings module):
File "D:/programs/levenberg.pyw", line 21
model=lambda tpl,x :(tpl[0]*(x**2) * n.sin(x))/((n.cos(x)**tpl[2]) *tpl[1])
RuntimeWarning: invalid value encountered in power

Warning (from warnings module):
File "C:\Python27\lib\site-packages\scipy\optimize\minpack.py", line 419
warnings.warn(errors[info][0], RuntimeWarning)
RuntimeWarning: Number of calls to function has reached maxfev = 800.
(array([ nan,  nan,  nan]), 5)
wiedzminYo
  • 531
  • 4
  • 11
  • 24
  • what error do you get? In what line? – matiasg May 19 '15 at 18:00
  • @matiasq Huge one,one of those: Traceback (most recent call last): File "D:/programs/levenberg.pyw", line 30, in param=scipy.optimize.leastsq(err,init,args=(x,y)) – wiedzminYo May 19 '15 at 18:02
  • Or File "D:/programs/levenberg.pyw", line 22, in model=lambda tpl,x :(tpl[0]*x^2 * n.sin(x))/((n.cos(x)^tpl[2]) *tpl[1]) TypeError: ufunc 'bitwise_xor' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe'' – wiedzminYo May 19 '15 at 18:03
  • @wiedzminYo, please use the `edit` link below your post to improve your question. When asking why an error occurred, always include the full traceback in your question. – cel May 19 '15 at 18:09

1 Answers1

1

It looks to me like you're using ^ instead of ** for exponentiation. Try:

model=lambda tpl,x :(tpl[0]*x**2 * n.sin(x))/((n.cos(x)**tpl[2]) *tpl[1])

Note that ^ is the bitwise xor operation in python. To raise things to a power, use **.

xnx
  • 24,509
  • 11
  • 70
  • 109
  • Yeah,my bad.Thanks for hint. But still I've got error "RuntimeWarning: invalid value encountered in power" – wiedzminYo May 19 '15 at 18:41
  • And something like that "RuntimeWarning: Number of calls to function has reached maxfev = 800. (array([ nan, nan, nan]), 5)" – wiedzminYo May 19 '15 at 18:42
  • Probably your function is singular somewhere: e.g. cos(x) = 0 for some x. – xnx May 19 '15 at 18:56
  • No,I checked it twice,there is no singularity – wiedzminYo May 19 '15 at 19:22
  • Ah, no - not necessarily in cos(x), but if cos(x) is negative for some x, then raising it to a non-integer power is going to cause problems for you. – xnx May 19 '15 at 20:23