Novo

Forum kao aplikacija na telefonu

Dodajte forum na početni ekran i koristite ga kao aplikaciju, sa menijem na dnu ekrana.

  • 4 odgovora
  • 6.889 pregleda

Najnovija ↓

Pomoć oko programa - π approximation 14.03.2017. u 22:57 · pre 117 meseci #1
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?
Re: Pomoć oko programa - π approximation 15.03.2017. u 15:44 · pre 117 meseci #2


Code:


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

Re: Pomoć oko programa - π approximation 15.03.2017. u 16:56 · pre 117 meseci #3
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! :)
Re: Pomoć oko programa - π approximation 15.03.2017. u 18:35 · pre 117 meseci #4
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:


\sum_{n=1}^{=\infty }(-1)^{n-1}*4/(2*n-1)

i korisnika pitas koliko clanova zeli
Prijavite se da biste odgovorili u ovoj temi.PrijavaRegistracija

Premeštanje teme