ara1123

pi

Oct 13th, 2017
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5.  
  6. long double approx1(int n);
  7. long double approx2(int n);
  8. long double approx3(int n);
  9.  
  10. int main()
  11. {
  12. int num1;
  13. num1 = 0;
  14.  
  15. printf("Enter number of terms to approximate pi to, or enter 0 to terminate: ");
  16. scanf("%d", &num1);
  17. puts(" ");
  18.  
  19. while (num1 != 0)
  20. {
  21. if(num1 == 1)
  22. { printf("First approximation of pi to %d term is %.8Lf \n\n", num1, approx1(num1));
  23. printf("Second approximation of pi to %d term is %.8Lf \n\n", num1, approx2(num1));
  24. printf("Third approximation of pi to %d term is %.8Lf \n\n", num1, approx3(num1));
  25. }
  26. else if (num1 > 1)
  27. { printf("First approximation of pi to %d terms is %.8Lf \n\n", num1, approx1(num1));
  28. printf("Second approximation of pi to %d terms is %.8Lf \n\n", num1, approx2(num1));
  29. printf("Third approximation of pi to %d terms is %.8Lf \n\n", num1, approx3(num1));
  30. }
  31. else
  32. printf("Wrong input, please try again. \n");
  33.  
  34.  
  35. printf("Enter number of terms to approximate pi to, or enter 0 to terminate: ");
  36. scanf("%d", &num1);
  37. }
  38.  
  39. printf("**Program Terminated***");
  40.  
  41. return 0;
  42. }
  43.  
  44.  
  45. long double approx1(int n)
  46. {
  47. long double pi, num, denom;
  48. pi = 0;
  49. denom = 1;
  50. num = 4;
  51. int i;
  52.  
  53.  
  54. for ( i = 1; i <= n; i = i + 1 )
  55. {
  56. if ( i % 2 != 0 ){
  57. pi = pi + num / denom;
  58. }
  59. else {
  60. pi = pi - num / denom;
  61. }
  62.  
  63. denom = denom + 2.0;
  64. }
  65.  
  66. return pi;
  67. }
  68.  
  69.  
  70. long double approx2(int n)
  71. {
  72. long double pi, num, denom;
  73. pi = 0;
  74. denom = 1;
  75. num = 1;
  76. int i;
  77.  
  78.  
  79. for ( i = 1; i <= n; i = i + 1 )
  80. {
  81. if (i % 2 != 0)
  82. {
  83. pi = pi + (12 * (num / (powl(denom, 2.0))));
  84. }
  85. else {
  86. pi = pi - (12 * (num / (powl(denom, 2.0))));
  87. }
  88.  
  89. denom = denom + 1.0;
  90. }
  91.  
  92. pi = sqrtl(pi);
  93.  
  94. return pi;
  95. }
  96.  
  97.  
  98. long double approx3(int n)
  99. {
  100. long double pi, num, denom, c1;
  101. pi = 0;
  102. num = 1;
  103. denom = 1;
  104. c1 = sqrtl(12.0);
  105. int i;
  106.  
  107.  
  108. for ( i = 0; i <= n; i = i + 1 )
  109. {
  110. if (i % 2 !=0)
  111. {
  112. pi = pi - (num/(denom*(powl(3.0, i))));
  113. }
  114. else {
  115. pi = pi + (num/(denom*(powl(3.0, i))));
  116. }
  117.  
  118. denom = denom + 2.0;
  119. }
  120.  
  121. return pi*c1;
  122. }
Add Comment
Please, Sign In to add comment