Python Error only length-1 arrays can be converted to Python scalars

≡放荡痞女 提交于 2021-01-28 06:30:19

问题


I am new to python coding and i am writing a code to calculate the sum of a series, i started by writing a function where the input is the number of iterations of the sum, but when i compile it gives me the error in the line under def G(i) : only length-1 arrays can be converted to Python scalars

Can you help me please

import matplotlib.pyplot as plt
import numpy as np
import scipy.special as sp
import pylab as pylab

def G(i):
    return (sum(((-1*(2*l+1))/(4*np.pi*(l**2+l)))*sp.legendre(l)(0.5)  for l in i))

pylab.ylim([-1,1])
sumrange = np.arange(1,70,1)
plt.plot(sumrange,G(sumrange),color='red')

回答1:


The problem stems from the fact that i is a sequence, not a single value. In your case, it's np.arange(1,70,1).

This doesn't make sense when you call range(1,i,1): i is not a single value. You can fix it by replacing for l in range(1,i,1) with for l in i.

There are some other problems, too—I'm not sure where cosgamma is defined. You should in the future provide a Minimum, Complete, and Verifiable example.



来源:https://stackoverflow.com/questions/43945729/python-error-only-length-1-arrays-can-be-converted-to-python-scalars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!