Case :
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.
Answer:
import math
trueValue = math.pi
def pi(n):
result = “”
apx = 0.0
for i in range(n):
apx += ((-1)**i)*4./((2*i)+1)
result += str(((-1)**i)*4)+“/”+str((2*i)+1)+” “
if(i != n – 1):
if(i%2==1):
result += “+”
else:
result += “= “
result += str(apx)
return apx, result
n = input(“Masukkan jumlah suku pertama approximation pi: “)
approx, res = pi(n)
print “Hasil approximation pi dengan”,n,“suku pertama =” ,res
print “Approximate =” ,approx
print “True Value =” ,trueValue
trueError = trueValue – approx
print “True Error =” ,trueError
print “Relative Error =” ,(trueError/trueValue)
print “Percent Relative Error =” ,(trueError/trueValue *100),“%”
this code created on python(x,y) with python version 2.7.5
And this code with gui from library graphics.pyc
from graphics import *
import math
def main():
win = GraphWin(“Approximation Pi”, 500, 350)
win.setBackground(‘pink’)
# Draw the interface
Text(Point(250,40), “Jumlah suku pertama approximation pi: “).draw(win)
Text(Point(110,225), “Approximation : “).draw(win)
Text(Point(110,250), “True Value : “).draw(win)
Text(Point(110,275), “True Error : “).draw(win)
Text(Point(110,300), “Relative Error : “).draw(win)
Text(Point(110,325), “Percent Relative Error : “).draw(win)
input = Entry(Point(250,80), 5)
input.setText(“0”)
input.draw(win)
button = Text(Point(250,150),“Approximate”)
button.draw(win)
Rectangle(Point(150,125), Point(350,175)).draw(win)
output1 = Text(Point(250,225),“”)
output2 = Text(Point(250,250),“”)
output3 = Text(Point(250,275),“”)
output4 = Text(Point(250,300),“”)
output5 = Text(Point(254,325),“”)
output1.draw(win)
output2.draw(win)
output3.draw(win)
output4.draw(win)
output5.draw(win)
# wait for a mouse click
win.getMouse()
# calculate input
trueValue = math.pi
def pi(n):
apx = 0.0
for i in range(n):
apx += ((-1)**i)*4./((2*i)+1)
return apx
approx = pi(eval(input.getText()))
trueError = trueValue – approx
rE = trueError/trueValue
pRE = rE*100
# display output and change button
output1.setText(“%0.10f” %approx)
output2.setText(“%0.10f” %trueValue)
output3.setText(“%0.10f” %trueError)
output4.setText(“%0.10f” %rE)
output5.setText(“%0.10f%%” %pRE)
button.setText(“Keluar”)
# wait for click and then quit
win.getMouse()
win.close()
this code created on python(x,y) with python version 2.7.5
And it’s for the code!
Approximation-Value-of-Pi-GUI
Here for screenshot

