[Solved] ‘float’ object has no attribute ‘__getitem__’ Python error
When I run the code
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
# Initial conditions
def f_func(eta,y_in):
y_out = np.zeros(3)
y_out[0] = y_in[1]
y_out[1] = y_in[2]
y_out[2] = -y_in[0]*y_in[2]/2
return y_out
eta = np.linspace(0,8,100)
X0 = [0,0,0.33206]
X = odeint(f_func,X0,eta)
I get the error
'float' object has no attribute '__getitem__'
When I run the following MATLAB program, everything works OK. The MATLAB function ode45 is equivalent to Pythons’ odeint.
main program:
clear
global beta
beta = 1;
initial_value = [0,0,1.2322];
eta = linspace(0,4,100)
[x_out, y_out] = ode45(@falkner_skan,eta,initial_value);
plot(x_out,y_out(:,2))
falkner_skan function:
function y_out = falkner_skan(x,y_in)
global beta
y_out(1,1) = y_in(2);
y_out(2,1) = y_in(3);
y_out(3,1) = -y_in(1)*y_in(3) - beta*(1-y_in(2)^2);
end
This and this and this thread does not seem to give me any guidance.
It seems as though y_in
is not a list but a float value. The error rises because you’re trying to get an item with obj[x]
of an object which doesn’t support it.
Looking at the documentation for odeint it says that the input function should take two arguments, the first being your data object and the second should be a float. Your implementation of f_func
is therefore wrong.
NumPy has float 64 object which has item() function, np.float64(10.5).item()
I had the same issue. According to documentation for odeint, in f_func(eta,y_in), change the order of eta and y_in, i.e. write it as f_func(y_in, eta) or set the argument tfirst to be True.