1

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')
outlaw
  • 241
  • 4
  • 16
  • Possible duplicate of [TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data](http://stackoverflow.com/questions/21687581/typeerror-only-length-1-arrays-can-be-converted-to-python-scalars-while-trying) – Arya McCarthy May 12 '17 at 20:23
  • Short version: use `np.sum` instead of `sum`. – Arya McCarthy May 12 '17 at 20:23
  • @aryamccarthy np.sum does not work, the problem is with the range inputs i think – outlaw May 12 '17 at 20:26
  • What do you mean, 'does not work'? What's the error? – Arya McCarthy May 12 '17 at 20:27
  • @aryamccarthy The same error as above, only length-1 arrays can be converted to Python scalars – outlaw May 12 '17 at 20:28
  • Copying your code in to python, changing to np.sum, it works fine on G(1), but that's because it doesn't execute the sum. Any value >1, it fails on `cosgamma undefined`. – Scott Mermelstein May 12 '17 at 21:01

1 Answers1

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.

Arya McCarthy
  • 8,554
  • 4
  • 34
  • 56
  • Yes, i forgot to tell that i replace cosgamma with any value i want, however for l in i is not working, it says: invalid syntax – outlaw May 12 '17 at 20:47
  • Be sure that you removed the right number of closing parentheses when you switched it: exactly 1. – Arya McCarthy May 12 '17 at 20:48
  • But this is till not working ( Invalid Syntax), are you sure that for l in range(1,i,1) is the same as for l in i ? – outlaw May 12 '17 at 20:59
  • It's exactly the point that they are different constructs, otherwise you'd still get the other error. Edit your post to include the latest version of your code. – Arya McCarthy May 12 '17 at 21:02