I created several programs in different languages to calculate pi using trapezoidal sums (C, Perl, and Python similar loops different results) and now I am trying to write one in Fortran. I don't know anything about the language and I wrote this:
program cpi
double precision n, val, pi
integer i, num
n = 1000
num = 1000
val = 0
do i = 1, num
val = val + ((1 - (i ** 2)) ** 0.5)
end do
pi = (2 / n)*(1 + (2 * val))
print *, pi
end program cpi
It returns NaN
when I compile it with gfortran
and run it. What does this mean and how can I change it to make it work? The C program I want to compare it to is this:
#include <stdio.h>
#include <math.h>
double n = 1000, a, h = 0, t, val, pi;
int main(void)
{
for(a = 1; a < n; ++a) {
t = a/n;
val = pow(1.0-(t*t), 0.5);
h+=val;
}
h = h*2.0;
pi = (2.0/n)*(1.0+h);
printf("%.20f\n", pi);
return 0;
}
Any input on fixing the Fortran program would be very nice.