I wrote scripts to calculate pi in python, perl and c. They all use the same algorithm (trapezoidal reimann sum of a circle with n subintervals) and the python and perl programs always get the same result when n is the same. However, the c program doesn't get the same answer like it should, it actually overestimates pi, which is impossible. What is wrong with the c program?
Python:
#!/usr/bin/python
n = 1000000
def f(x):return (1-(float(x)**2))**float(0.5)
val = 0
for i in range(n):
i = i+1
val = val+f(float(i)/float(n))
val = val*2
pi = (float(2)/n)*(float(1)+val)
print pi
Perl:
#!/usr/bin/perl
$n = 1000000;
$h = 0;
for($a = 1; $a < $n; ++$a){$t = $a/$n;$val = (1-(($t)**2))**0.5;$h+=$val;
}
$h = $h*2;
$pi = (2/$n)*(1+$h);
printf "%.11f", $pi;
C:
#include <stdio.h>
#include <math.h>
int main()
{int count, n = 1000000;double pi;double val = 0.0, p = 0.50, x = 1.0, four = 4.0;for(count = 1; count < n; ++count){val += (pow(x-(((double)count/(long double)n)*((double)count/(long
double)n)), p));}pi = (val + x) * (four/(long double)n);printf("%.11f", pi);
}
Results: C = 3.14159465241 Perl and Python = 3.14159265241