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

0

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

  

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))
    
asked by anonymous 06.10.2017 / 17:14

1 answer

0

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

In this way, when you do (x-y)/2 creates a new array, so the math.fabs function can not operate since it expects a single value (a scalar not a vector).

You can do 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()
    
06.10.2017 / 19:10