Calculation of the sum of a series?

This is my task, and for my life I do not seem to think about how to do this. This is the code that I still have:

sum = 0
k = 1
while k <= 0.0001:
     if k % 2 == 1:
       sum = sum + 1.0/k
     else:
      sum = sum - 1.0/k
 k = k + 1
 print()

This is my assignment:

Create a python program called sumseries.py that does the following: Put comments at the top of your program with your name, date, and program description.

Write a program to calculate and display the sum of a series:

1 - 1/2 + 1/3 - 1/4 + ...

until a deadline of less than 0.0001 is reached.

The answer with 10,000 iterations looks like 0.6930971830599583

I ran the program with iterations of 1,000,000,000 (billion) and came up with the series 0.6931471810606472. I need to create a loop for programmable series creation.

+4
source share
5

, :

Answer = sum(1.0 / k if k % 2 else -1.0 / k for k in range(1, 10001))

:

  • generator, " ",
    • 1.0 / k if k % 2 else -1.0 / k 1.0 / k, k -1.0 / k (a - b a + (-b))
    • for k in range(1, 10001) k 1 () 10001 ()
  • sum ( iterable, ), ,

:

Answer = 0
for k in range(1, 10001):
    if k % 2:
        Answer += 1.0 / k
    else:
        Answer -= 1.0 / k

    # or simply:
    # Answer += 1.0 / k if k % 2 else -1.0 / k
+5

, , ,

while k <= 0.0001:

:

 while term <= 0.0001:

, 1/k

+2

, , . , , . , , 10000 , .

10000, . (1, -1/2, 1/3, -1/4,...) 0,0001.

, , , , . , , (-1)**(k-1)/k, 1/k 1/k^2.

" 0,0001" . , ( ) 0,0001. -1/2, -.

, , .;) , Python2.x float.

def term(k):
    return (-1)**(k - 1) / float(k)

err = 0.0001

def terms():
    k = 1
    t = term(k)
    while abs(t) >= err:
        yield t
        k += 1
        t = term(k)

print(sum(terms()))
0
source

Here is the answer your teacher is looking for for full credit.
before <.0001 means while> = 0.0001 This changes your code the least, so it makes it a fix for what you wrote

sum = 0
k = 1
while 1.0/k >= 0.0001:
     if k % 2 == 1:
       sum = sum + 1.0/k
     else:
       sum = sum - 1.0/k
     k = k + 1
print(sum)
0
source

An absolutely simple way would be the following sum((-1)**(k) / k for k in range(1, 10001))

0
source

Source: https://habr.com/ru/post/1654988/


All Articles