[ wraith46 @ 14.03.2017. 21:57 ] @
Radim po knjizi Python Programming: An Introduction to Computer Science (2nd Edition) by John Zelle.

Imam manjih problema sa 15. zadatkom na 64. strani:

Citat:
Write a program that approximates the value of π by summing the terms of this series: 4/1 - 4/3 + 4/5 - 4/7 + 4/9 - 4/11 + ... The program should prompt the user for n, the number of terms to sum, and then output the sum of the first n terms of this series. Have your program subtract the approximation from the value of math.pi to see how accurate it is.


Pokušavam to da uradim na sledeći način:

Code:
# pi_approximation
#   Program which approximates the value of Pi by summing the terms of
#   this series: 4/1 - 4/3 + 4/5 - 4/7

import math

def main():

    print("Welcome to Pi approximation!\n")
    
    n = int(input("Enter the number of terms to sum: "))
    
    approx = 0

    for i in range(1, n+1, 2):
        approx += 4 / i - 4 / (i+2)

    print("Approximate value of pi is: " + str(approx))
    
    print("Deviation from Pi is: " + str(math.pi - approx))

main()


Nisam siguran da li je ovo ispravno?
[ zema @ 15.03.2017. 14:44 ] @


Code:


for i in range(1, n+1):
  if i%2 != 0:
    approx += 4 / (2*i-1)
  else:
    approx -= 4 / (2*i-1)

[ wraith46 @ 15.03.2017. 15:56 ] @
Kasniš zemo :) skočih na StackOverflow, rekoše mi da je greška u suštini

Citat:
for i in range(1, n+1, 2): should be for i in range(1, n+1, 4): since you sum the i part AND the i+2 part


E sad, možda da se uključi neko treći da razmotrimo šta je "ispravnije"...pošto sam ja još uvek newbie.

Hvala što si se angažovao, svakako! :)
[ zema @ 15.03.2017. 17:35 ] @
imas ovaj zahtev:

The program should prompt the user for n, the number of terms to sum, and then output the sum of the first n terms of this series

ako ti u for petlji stoji:

for i in range(1, n+1, 4)

imaces clanove 1,5,9,13...

i ako korisnik zeli npr prva 4 clana dobice: 4/1 - 4/5

dakle for petlja treba da broji od 1 do n+1 bez preskakanja



tebi je u zadatku dat red:



i korisnika pitas koliko clanova zeli
[ wraith46 @ 15.03.2017. 19:12 ] @
Razumem. Hvala mnogo još jednom!