Error "only length-1 arrays can be converted to Python scalars" when using ndarray as a function

1

I have the following code in Python, I have problems in the penultimate line, I do not know if calling the method initial there is an error.

Can you help me?

import numpy as np
from math import exp,ceil

def initial (x):
   init=0.09*exp(-x**2/50);
   return init

a = -20;
b= 20;
T=4;
M=500;
rhom=0.2;
n=10;
drho=rhom/n;
rho=np.linspace(0,rhom,n+1);#lim inf, lim sup, "step"'

def flux(rho):
    vf=15;
    rhomax=0.2;
    fl=vf*(1-rho/rhomax)*rho;
    return fl

frho=flux(rho)
qmax=max(frho);#Busca el máximo de la lista
s=np.argmax(frho)#devuelve el índice del valor máximo
rhostar=rho.item(s)#devuelve el elemento en la posición "i"
lamda=max(abs(frho[1:n]-frho[0:n-1]))/drho;
h=(b-a)/M;
ka=0.5*h/lamda;
N=ceil(T/ka);
k=T/N;
kio=np.insert(np.arange(a+h/2,b-h/2,h),len(np.arange(a+h/2,b-h/2,h)),b-h/2)# np.insert(lista,length,valor_a_agregar)
xticks=kio.transpose();
U=np.zeros((M,N+1));
U[:,1]=initial(xticks);
print(U[:,1])

And I got this error:

Traceback (most recent call last):
  File "C:\Users\ALEX EDUARDO\Documents\HolaMundoPython.py", line 35, in <module>
    U[:,1]=initial(xticks);
  File "C:\Users\ALEX EDUARDO\Documents\HolaMundoPython.py", line 5, in initial
    init=0.09*exp(-x**2/50);
TypeError: only length-1 arrays can be converted to Python scalars
    
asked by Alex Pozo 01.02.2018 в 02:29
source

1 answer

0

The problem is found in the line init=0.09*exp(-x**2/50); since math.exp of the standard library expects only a scalar as an argument, it is not meant to work with arrays. NumPy usually provides alternatives to do the same tasks on arrays, in this case you should use numpy.exp :

import numpy as np
from math import ceil


def initial(x):
    init = 0.09 * np.exp(-x**2/50)
    return init


a = -20
b = 20
T = 4
M = 500
rhom = 0.2
n = 10
drho = rhom / n
rho = np.linspace(0, rhom, n+1)  # lim inf, lim sup, "step"


def flux(rho):
    vf = 15
    rhomax = 0.2
    fl = vf * (1 - rho / rhomax) * rho
    return fl


frho = flux(rho)
qmax = max(frho)  # Busca el máximo de la lista
s = np.argmax(frho)  # Devuelve el índice del valor máximo
rhostar = rho.item(s)  # Devuelve el elemento en la posición "i"
lamda = max(abs(frho[1:n] - frho[0:n-1])) / drho
h = (b - a) / M
ka = 0.5 * h / lamda
N = ceil(T/ka)
k = T / N
kio = np.insert(np.arange(a+h/2, b-h/2, h), len(np.arange(a+h/2, b-h/2, h)), b-h/2)
xticks = kio.transpose()
U = np.zeros((M, N+1))
print(type(xticks))
U[:, 1] = initial(xticks)
print(U[:, 1])
  

Note: in Python you do not have to use; to delimit each instruction (in fact it is not considered correct by convention). I recommend looking at PEP-8 to see the code style guides.

    
answered by 01.02.2018 / 03:07
source