0

I am trying to develop a function that calculates the sum of sines.

The first function that I tried was:

def S(t,n,T):
    return (4/pi)*sum((1/(2*i-1))*sin(2*(2*i-1)*pi*t/T) for i in range(1,n+1))

and then I got an answer of 0.2381 when I called the function using the arguments below:

S(0.01*2*pi,3,2*pi)

As I am relatively new to Python I tried to amend this code to:

def S1(t1,n1,T1):
    
    s1 = 0
    
    for i in range(1,n1+1):
        s1 = s1 + (4/pi)*sum((1/(2*i-1))*sin(2*(2*i-1)*pi*t1/T1))
    return s1

but when I call the function S1 using the same arguments I get an error saying that:

TypeError: 'float' object is not iterable. 

Can someone explain why this is? I reviewed some of the other answers in relation to this TypeError but I do not understand them.

2
  • 2
    What do you expect to get from sum((1/(2*i-1)) ...?
    – pho
    Commented Apr 20, 2021 at 13:56
  • You may just want to get rid of sum(), since you are explicitly summing in the for loop. Commented Apr 20, 2021 at 14:20

2 Answers 2

0

The answer is pretty trivial: sum() requires an iterable as argument, while in S1 you are passing it a float.

In S() it works well since with for i in... builds a collection which is then passed to sum(), while in the second case you are fixing i and getting a float to pass to sum() at every cycle.

1
  • Hi, thanks for your answers. I appreciate the responses which are helping me to learn and hopefully contribute myself in time.
    – Crowls
    Commented Apr 20, 2021 at 15:13
0

The function sum() requires an iterable as argument, but in S1 you are passing it a float.

Here's the solution:

def S1(t1, n1, T1):
    results = []
    for i in range(1, n1 + 1):
        results.append((1 / (2 * i - 1)) * sin(2 * (2 * i - 1) * pi * t1 / T1))
    return (4 / pi) * sum(results)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.