Reputation: 27
so I'm trying to calculate value of pi using recursion. My code looks like this:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <malloc.h>
double pi (int n){
double s = 0;
s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) );
if( n > 0 ) {
pi( n - 1 );
}
return s;
}
int main(void) {
int n,i;
float *A;
scanf("%d", &n);
A = (float*)malloc( n *sizeof(float) );
for( i = 0 ; i < n; i++ ) {
A[i] = pi( i + 1 );
}
for( i = 0; i < n; i++ ) {
printf( "%f\n", A[i] );
}
return 0;
}
for value of n = 1
, it returns the expected answer, pi = 4
, but for any other value it computes that pi = 0
. Anyone care to explain why?
Upvotes: 0
Views: 1185
Reputation: 321
You can do it like this:
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <malloc.h>
double pi (int n){
double s = 0;
if( n > 0 ) {
s = s + 4 * ( pow(-1,n+1 ) * (1/(2*(double)n-1) ) );
s += pi( n - 1 );
}
return s;
}
int main(void) {
int n,i;
float *A;
scanf("%d", &n);
A = (float*)malloc( n *sizeof(float) );
for( i = 0 ; i < n; i++ ) {
A[i] = pi( i + 1 );
}
for( i = 0; i < n; i++ ) {
printf( "%f\n", A[i] );
}
return 0;
}
These are the things that you are doing wrong:
In the function pi, you are only returning the value of s from the first recursive call. The value of s from successive recursive calls is lost.
..
In this piece of code 1/(2*n-1) , since n is an integer, integer division takes place. You need to cast n to a double to avoid losing digits after the floating point
..
The piece of code,
s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) );
should be placed inside the if conditionif( n > 0 )
This is because, when n equals 0, you will simply be adding another 4 to the value of s.
s = s + 4 * ( pow(-1, 0+1 ) * (1/(2*0-1) ) );
s = s + 4 * ( -1 * -1)
s = s + 4
Upvotes: 0
Reputation: 1297
use s = s + 4 * ( pow(-1,n+1 ) * (1.0/(2*n-1) ) );
instead of s = s + 4 * ( pow(-1,n+1 ) * (1/(2*n-1) ) );
because if n=2 , the (1/(2*n-1)) part will give 1/3 , and as both 1 and 3 are integers, result will be converted to integer that is 0, thats why u get a 0.
Upvotes: 1