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

Asked

Viewed 3,283 times

0

Good afternoon. I made a small algorithm on Python, appeared the following error:

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

Someone could help me. Follow the code.

import numpy as np
import math
x=np.ones((3,1))
y=np.ones((3,1))
err=[]
for k in range(3,15):
    x=np.append(x,1.074*((x[k-1])**2)-2.042*x[k-2]*x[k-3])
    y=np.append(y,1.074*y[k-1]*y[k-1]-2.042*y[k-2]*y[k-3])
    err.append(math.fabs((x-y)/2))

1 answer

0


Operations with Numpy arrays are vector arrays. For example: np.array([1, 2, 3]) + np.array([4, 5, 6]) returns array([5, 7, 9]).

That way, when you do (x-y)/2 creates a new array and thus the function math.fabs cannot operate since it expects a single value (a scalar and not a vector).

You can do it like this:

import numpy as np

x=np.ones((3,1))
y=np.ones((3,1))

for k in range(3,15):
    x=np.append(x,1.074*((x[k-1])**2)-2.042*x[k-2]*x[k-3])
    y=np.append(y,1.074*y[k-1]*y[k-1]-2.042*y[k-2]*y[k-3])

err = np.abs((x-y)/2).tolist()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.