-4

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.

Alexander Vogt
  • 17,879
  • 13
  • 52
  • 68
Paul
  • 88
  • 9
  • I must admit that I wondered "wt*?" when I saw four languages in the tags. :) While there are some connection, the question is still about fortran so please remove python, c and perl. – klutt Jul 10 '17 at 16:27
  • @klutt I fixed the question. Thanks for the advice! – Paul Jul 10 '17 at 16:35
  • 1
    The other versions are helpful for showing what it is supposed to be compared to. – Paul Jul 10 '17 at 16:36
  • `((1 - (i ** 2)) ** 0.5)` attempts the root of a negative number. I suspect you want some sort of `t` rather than `i`. – chux - Reinstate Monica Jul 10 '17 at 16:38
  • Thanks, that is a simple and obvious mistake. It should be i / n instead of i in that spot. – Paul Jul 10 '17 at 16:41

1 Answers1

1

Thank you to @chux, the program works now:

program cpi
double precision n, val, pi
integer i, num
n = 1000
num = 1000
val = 0
do i = 1, num
  val = val + ((1 - ((i / n) ** 2)) ** 0.5)
end do
pi = (2 / n)*(1 + (2 * val))
print *, pi
end program cpi
Paul
  • 88
  • 9
  • 1
    For some value of "works". I suggest you learn why in Fortran ((1 - ((i / n) ** 2)) ** 0.5) is evaluated in "single precision", and then I suggest you learn about the Fortran kind mechanism. – Ian Bush Jul 11 '17 at 07:22