'Pi calculator using the Leibniz's formula in C. What is wrong?
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;
}
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jim Rogers |
