1

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!

Y Yen
  • 13
  • 3
  • Next time try to introduce better what you are trying to do, it may be helpful to others. – Douglas Ferreira Oct 18 '21 at 13:58
  • When you get errors like this, pay attention to where they occur. Show us the `traceback`, the full error message. In this case it pointed to a `math.exp` line. Did you take time to look up that function? Checking the documentation before posting a question. – hpaulj Oct 18 '21 at 16:30

1 Answers1

2

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.

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76