Skip to content Skip to sidebar Skip to footer

Error "can't Multiply Sequence By Non-int Of Type 'float'"

In the following code, when I try to run the line 'x01 = rk4(x01,t1[-1],h1,fallParabola),' an error pops up saying 'can't multiply sequence by non-int of type 'float'.' I am wonder

Solution 1:

You're multiplying h by a tuple, and not a numpy array in your Runge-Kutta definition:

def rk4(f,t,h,g):
    k1 = h*g(t,f)
    k2 = h*g(t+0.5*h, f+0.5*k1)
    k3 = h*g(t+0.5*h, f+0.5*k2)
    k4 = h*g(t+h, f+k3)
    return f + k1/6. + k2/3. + k3/3. + k4/6.

Here g is the function you're passing in, which is fallParabola() which by your definition returns a tuple:

def fallParabola(t,f):
    g =10
    px = f[0]
    py = f[1]
    vx = f[2]
    vy = f[3]
    slope = slope1 * (px-shift1)
    theta = sp.arctan(np.abs(slope))
    acc = np.array([vx,vy,g*sp.sin(theta)*sp.cos(theta), 
        g*sp.sin(theta)*sp.sin(theta)])
    return acc,slope

You should modify this definition to return a numpy array so you can multiply through it:

return np.array([acc, slope])

The reason for the specific error message about non-int is simply because you can multiply a tuple by an integer, but this doesn't multiply the values inside the tuple. First, a tuple is immutable so you can't change the values anyways, but in general for sequences, multiplying by an integer repeats the sequence by the multiplier. For e.g.

>>>tup = (5, 4)>>>tup*3
(5, 4, 5, 4, 5, 4)

If you multiply here by a float, it doesn't make sense of course, and you get the same error you've got:

>>> tup*3.14
Traceback (most recent calllast):
  File "<stdin>", line 1, in<module>
TypeError: can't multiply sequence by non-int of type 'float'

Also as an aside, your fallParabola() function is not defined well IMO. Currently you have it taking global variables (like slope1, shift1) but it would be best to pass these values into the function. Generally global variables are not evil in Python, but if a function uses some parameters, it's best practice to send those parameters in so you know what it's using. And if you need to update the variables like slope1 as time goes on, this provides an easier interface to do so.

Post a Comment for "Error "can't Multiply Sequence By Non-int Of Type 'float'""