fork download
  1. import math;
  2. inptTol = float(input("Enter the tolerance: "))
  3. print()
  4.  
  5. term = 1
  6. divNum = 3
  7. npower = 1
  8. sumPi = 0.0
  9. count = 0
  10.  
  11. while abs(term) > inptTol:
  12. sumPi += term
  13. term = ((-1)**npower)/(divNum * (3**npower))
  14. divNum += 2
  15. npower += 1
  16. count += 1
  17. print( term )
  18.  
  19. sumPi = math.sqrt(12) * sumPi
  20. pythonPi = math.pi
  21. approxError = abs (sumPi - pythonPi)
  22.  
  23. print("The approximate value of pi is %.14e\n" \
  24. " Python's value of pi is %.14e\n"
  25. "The error in the approximation of pi is %.6e\n"
  26. "The number of terms used to calculate the value of pi is %g " %
  27. (sumPi, pythonPi, approxError, count))
Success #stdin #stdout 0.02s 9984KB
stdin
1e-17
stdout
Enter the tolerance: 
-0.1111111111111111
0.022222222222222223
-0.005291005291005291
0.0013717421124828531
-0.0003741114852225963
0.00010551862403714256
-3.0483158055174515e-05
8.965634722110152e-06
-2.673961232910045e-06
8.064327527823946e-07
-2.4543605519464186e-07
7.526705692635683e-08
-2.3230573125418773e-08
7.209488211336861e-09
-2.2481199798792364e-09
7.039567613763265e-10
-2.212435535754169e-10
6.976148085711344e-11
-2.20613230060957e-11
6.995053636079125e-12
-2.2232341013894893e-12
7.0814123229443e-13
-2.2600252094503082e-13
7.225930941779898e-14
-2.314187033641928e-14
7.422864070172221e-15
-2.384313913449259e-15
7.668845920450834e-16
-2.4696283472638276e-16
7.962189753473542e-17
-2.5698072749306142e-17
8.302454272852753e-18
The approximate value of pi is 3.14159265358979e+00
       Python's value of pi is 3.14159265358979e+00
The error in the approximation of pi is 8.881784e-16
The number of terms used to calculate the value of pi is 32