user4612744 user4612744 - 1 year ago 115
Python Question

"only length-1 arrays can be converted to Python scalars"-error with float conversion-function

When running this program, I receive the error "TypeError: only length-1 arrays can be converted to Python scalars", specifically referring to line 9, where the x1-variable is assigned.

I'm kind of clueless here what it means in this context. I worked with a very similar piece of code for a previous assignment, where it all worked fine. I took in a vector as an argument to the function and computed all the values simultaneously.

Note: After I removed the floating it seems to work fine, but I have no clue why. Can anyone explain?

import matplotlib.pyplot as plt
import numpy as np
g = 9.78
p = 1000
h = 50
s = 7.9 * 10**-2

def water_wave_speed(l):
x1 = float(g * l/(2 * np.pi))
x2 = 1 + s * float((4 * np.pi**2)/(p * g * l**2))
x3 = float((2 * np.pi * h)/l)
c = np.sqrt(x1 * x2 * np.tanh(x3))
return c

l_values = np.linspace(0.001, 0.1, 10)
c_values = water_wave_speed(l_values)
plt.plot(l_values, c_values)

Answer Source

Drop all of those float calls and your code should work (as floats). You're trying to coerce numpy arrays into single float values which isn't going to work.