1

I'm new to coding and was given an assigment to approximate the value of pi through the Leibniz's formula. This is what I wrote but it's taking forever to compile. I've tried to debug it but with no success.

#include <stdio.h>
#include <math.h>

float pi(int n);

int main(){

    int n;

    printf("enter the number of terms: ");
    scanf("%f", &n);

    if(n < 1){
        printf("the number needs to be greater than 0. try again: ");
        scanf("%f", &n);
        printf("%.6f", pi(n));
    }
    else{
        printf("%.6f", pi(n));
    }

    return 0;
}

float pi(int n){

    float sum = 1; //first element of summation is one

    for(int i = 1; i < n; i++){
        sum += pow(-1, i)/(2 * i) + 1;
    }

    return 4 * sum;
}
eve
  • 11
  • 1
  • 1
    Please turn on compiler warnings (`-Wall -Wextra`). [Extra Reading](https://stackoverflow.com/questions/57842756/why-should-i-always-enable-compiler-warnings) – SuperStormer Feb 25 '22 at 00:33
  • I think you mean it's taking forever to run. Compiling should be instant. – Barmar Feb 25 '22 at 00:33
  • 2
    `scanf("%f", &n);` `%f` format is for `float`, but `n` is `int`. You should use `%d`. – Barmar Feb 25 '22 at 00:33
  • `(2 * i) + 1` needs parenthese around it: `((2 * i) + 1)`. Your code is adding 1 every time through the loop, instead of adding to the denominator of the equation. – Barmar Feb 25 '22 at 00:35
  • ty for the feedback guys! – eve Feb 25 '22 at 00:41
  • A loop would make more sense that just trying a second time. `while (1) { get input; if (n > 0) break; print error message; }` – ikegami Feb 25 '22 at 01:23

1 Answers1

0

Your formula for the Leibniz algorithm for Pi is flawed. You need to calculate

1 - 1/3 + 1/5 - 1/7 + 1/9 ... = Pi / 4

An Ada solution for this problem is:

with Ada.Text_IO;         use Ada.Text_IO;
with Ada.Integer_Text_IO; use Ada.Integer_Text_IO;

procedure Main is
   package lf_io is new Float_IO(Long_Float);
   use lf_io;

   function pi_approx (Terms : Positive) return Long_Float is
      Sum : Long_Float := 1.0;
      Act    : Boolean := True;
      Factor : Long_Float   := 3.0;
   begin
      for I in 1 .. Terms loop
         if Act then
            Sum := Sum - 1.0 / Factor;
         else
            Sum := Sum + 1.0 / Factor;
         end if;
         Factor := Factor + 2.0;
         Act    := not Act;
      end loop;
      return 4.0 * Sum;
   end pi_approx;

   N : Positive;

begin
   Put ("Enter the number of terms: ");
   Get (N);
   Put (Item => pi_approx (N), Exp => 0, Aft => 8, Fore => 1);
end Main;

In the solution the Boolean variable named Act is initialized to TRUE. It controls the alternating subtraction and addition of the terms. The first factor used for division is 3.0. All the factors are odd numbers.

Use type double for more accuracy. The closest approximation to Pi takes over 60,000,000 terms.

Program output:

Enter the number of terms: 60000000
3.14159267
Jim Rogers
  • 4,822
  • 1
  • 11
  • 24