Petr Petrov Petr Petrov - 1 month ago 12
Python Question

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

I have a func

f(x) = sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)


I need to solve system of linear equations

w0 + w1x1 + w2(x1)**2 + ... + wn(x1)**n = f(x1)


I solve that but I have a problem with plot it

from math import sin, exp
from scipy import linalg
import numpy as np

b = []
def f(x):
return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

for i in [1, 15]:
b.append(f(i))

A = []

for i in [1, 15]:
ij = []
x0 = i ** 0
x1 = i ** 1
ij.append(x0)
ij.append(x1)
A.append(ij)

matrix = np.array(A)
b = np.array(b).T

x = linalg.solve(matrix, b)
from matplotlib import pyplot as plt
plt.plot(x, f(x))


But it returns

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


How can I solve this problem?

Answer Source

math.sin and math.exp expect scalar inputs. If you pass an array, you get a TypeError

In [34]: x
Out[34]: array([ 3.43914511, -0.18692825])

In [35]: math.sin(x)
TypeError: only length-1 arrays can be converted to Python scalars

from math import sin, exp loads sin and exp from the math module and defines them as functions in the global namespace. So f(x) is calling math's version of the sin function on x which is a NumPy array:

def f(x):
    return sin(x/5.0)*exp(x/10.0) + 5*exp(-x/2.0)

To fix the error, use NumPy's sin and exp functions instead.

import numpy as np
def f(x):
    return np.sin(x/5.0)*np.exp(x/10.0) + 5*np.exp(-x/2.0)