Home python Why the error “ValueError: setting an array element with a sequence” is...

Why the error “ValueError: setting an array element with a sequence” is thrown




Why the error occurs:

ValueError: setting an array element with a sequence

and how to fix it?

import math
import numpy
import matplotlib.pyplot as plt
from scipy.optimize import minimize
def f (x):
  return math.sin (x / 5) * math.exp (x / 10) + 5 * math.exp (-x / 2)
f2 = numpy.vectorize (f)
x0 = [14., 16., 13., 15., 17.]
res = minimize (f2, x0)
print res

Answer 1, authority 100%

From the documentation :

x0: ndarray, shape (n,)

Initial guess. Array of real elements of size (n,), where ‘n’ is the number of independent variables .

Because f (x) is a function of one variable, then x0 must also consist of one element.


In [255]: minimize (f, [14.])
Out [255]:
   fun: -11.898894665981317
 hess_inv: array ([[18.83373626]])
   jac: array ([0.])
 message: 'Optimization terminated successfully.'
   nfev: 24
   nit: 2
   njev: 8
  status: 0
 success: True
    x: array ([25.88019315])

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions