Home > Mobile >  'only length-1 arrays can be converted to Python scalars' error
'only length-1 arrays can be converted to Python scalars' error

Time:10-19

I have such Python code

import numpy as np
import matplotlib.pyplot as plt
import math
from scipy import optimize as opt

def func1(x):
    f1 = math.exp(x-2) x**3-x
    return f1

solv1_bisect = opt.bisect(func1, -1.5, 1.5)

x1 = np.linspace(-1.5,1.5) 
y1 = func1(x1)
plt.plot(x1,y1,'r-')
plt.grid()

print('solv1_bisect = ', solv1_bisect)

and I've got the error message such as

TypeError: only length-1 arrays can be converted to Python scalars

Please help me to fix it, Thanks!

CodePudding user response:

The problem is that you are using math.exp that expects a Python scalar, for example:

>>> import numpy as np
>>> import math
>>> math.exp(np.arange(3))  

Traceback (most recent call last):
  File "path", line 3331, in run_code
    exec(code_obj, self.user_global_ns, self.user_ns)
  File "<ipython-input-10-3ac3b9478cd5>", line 1, in <module>
    math.exp(np.arange(3))
TypeError: only size-1 arrays can be converted to Python scalars

Use np.exp instead:

def func1(x):
    f1 = np.exp(x - 2)   x ** 3 - x
    return f1

The difference between np.exp and math.exp is that math.exp works with Python's numbers (floats and integers) while np.exp can work with numpy arrays. In your code the argument x is a numpy array, hence the error.

  • Related