TM1 – Scientific Computing Lab

Nama : Ryo Hadinata
NIM    : 1601250023
04PAW

IT-Math
Bina Nusantara University

Case Study:

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.

Ans:

import math

def function(n):
 result = ((-1.0)**(n+1)) * (4.0/(2*n-1))
 return result

def main():
 result = 0
 n = int(input("Please input n: "))
 for x in range(1, n+1):
 result = result + function(x)
 print("\n\nResult: ")
 print("============")
 print("Value of math.pi = " + str(math.pi))
 print("Approximation by program = " + str(result))
 print("Math.pi - Approximation = " + str(math.pi - result))
 print("True Fractional Relative Error = " + str((math.pi-result)/math.pi))
 print("True Percent Relative Error = " + str(((math.pi-result)/math.pi)*100) + "%")

main()

Click to download code (*.py)

n = 10
Output:

Please input n: 10


Result: 
============
Value of math.pi = 3.14159265359
Approximation by program = 3.04183961893
Math.pi - Approximation = 0.0997530346604
True Fractional Relative Error = 0.0317523771092
True Percent Relative Error = 3.17523771092%
This entry was posted in Scientific Computing Lab Assignments and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *