简体   繁体   中英

How to convert a list in a float?

My code has the following error: float () argument must be a string or a number, not 'list'.

I know that my ww function is a list of values, but I do not know how to convert it to float, since ww is a function. I tried list comprehension, following the question in:

TypeError: float() argument must be a string or a number, not 'list' python

But it didn't work.

def func(n):
    return 2/(n+1)

def ww(n):
    return [-1 + i*func(n) for i in range(0,n+1)] 

def g(x,y):
    return x**2 + y

This g(x,y) is actually spherical harmonics, but I put this for simplicity.

def integral(n):
    return [np.pi*func(n)*(1 + math.cos(np.pi*(-1 + i*func(n))))*g(np.pi*i,ww(n)) for i in range(0,n+1)]   

Your ww function returns a list of floats, which are then passed into g() . The calculation fails because you cannot add a list to a number.

It is not possible to "convert a list of floats to a float" without performing some sort of operation on the numbers — eg "add", "subtract", "multiply".

However, you can convert the list to an numpy array, which can be operated on as a whole. Multiplying an array of numbers by a single number multiplies each value, returning the result.

For example:

>>> a = np.array([1.0,2.0,3.0])
>>> b = 2
>>> b ** 2 + a
array([5.0, 6.0, 7.0])

If you wrap the return value of ww to convert to a numpy array, the subsequent calculation in g() should work.

def ww(n):
    return np.array([-1 + i*func(n) for i in range(0,n+1)])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM