Tugas Manidri 1 Scientific Computing Lab

Name : Benny Y. Pratama

NIM : 1601236246

Class : 04PAW

Computer Science – Mathematics | BINUS University

 

Question :

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

def main():

final = 0

n = int(input(“Enter the number you want to sum :  “))

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

divider = 2 * i – 1

if i % 2 == 0:

final = final – (4.0/divider)

else:

final = final + (4.0/divider)

print(“The result is :“)

print(“The result from math.pi is = ” + str(math.pi))

print(“The total from the first %d number = ” %(i) + str(final))

print(“True error (Et) = “, str(math.pi-final))

print(“True fractional relative error = “, str((math.pi-final)/math.pi))

print(“True percent relative error = “, str(((math.pi-result)/math.pi)*100), “%”)

main()

Respond to this post

You must be logged in to post a comment.