From 6fb9f35bcae368e7b67b6c3b7041999774f64918 Mon Sep 17 00:00:00 2001 From: Xin Li <lxin@kth.se> Date: Mon, 8 Oct 2018 17:57:33 +0200 Subject: [PATCH] updated pi code --- intro_lab/pi.c | 15 ++++++++------- intro_lab/pi.f90 | 12 ++++++------ 2 files changed, 14 insertions(+), 13 deletions(-) diff --git a/intro_lab/pi.c b/intro_lab/pi.c index 4307c6a..59a6b6d 100644 --- a/intro_lab/pi.c +++ b/intro_lab/pi.c @@ -2,6 +2,8 @@ #include <math.h> #include <omp.h> +#define NSTEPS 134217728 + /* * This program computes pi as * \pi = 4 arctan(1) @@ -9,24 +11,23 @@ */ int main(int argc, char** argv) { - unsigned long nsteps = 100000000; - double dx = 1.0 / nsteps; - + long i; + double dx = 1.0 / NSTEPS; double pi = 0.0; + double start_time = omp_get_wtime(); - unsigned long i; - for (i = 0; i < nsteps; i++) + for (i = 0; i < NSTEPS; i++) { double x = (i + 0.5) * dx; pi += 1.0 / (1.0 + x * x); } - pi *= 4.0 * dx; + pi *= 4.0 * dx; double run_time = omp_get_wtime() - start_time; double ref_pi = 4.0 * atan(1.0); printf("pi with %ld steps is %.10f in %.6f seconds (error=%e)\n", - nsteps, pi, run_time, fabs(ref_pi - pi)); + NSTEPS, pi, run_time, fabs(ref_pi - pi)); return 0; } diff --git a/intro_lab/pi.f90 b/intro_lab/pi.f90 index c045292..127a5fe 100644 --- a/intro_lab/pi.f90 +++ b/intro_lab/pi.f90 @@ -8,25 +8,25 @@ use omp_lib implicit none -integer(kind=8) :: nsteps, i +integer(kind=8), parameter :: NSTEPS = 134217728 + +integer(kind=8) :: i real(kind=8) :: dx, x, pi, ref_pi real(kind=8) start_time, run_time -nsteps = 100000000 -dx = 1.0D0 / nsteps +dx = 1.0D0 / NSTEPS pi = 0.0D0 start_time = OMP_GET_WTIME() -do i = 1, nsteps +do i = 1, NSTEPS x = (i - 0.5D0) * dx pi = pi + 1.0D0 / (1.0D0 + x * x) enddo pi = pi * 4.0D0 * dx - run_time = OMP_GET_WTIME() - start_time ref_pi = 4.0D0 * atan(1.0D0) -print '("pi with ", i0, " steps is ", f16.10, " in ", f12.6, " seconds (error=", e12.6, ")")', nsteps, pi, run_time, abs(ref_pi - pi) +print '("pi with ", i0, " steps is ", f16.10, " in ", f12.6, " seconds (error=", e12.6, ")")', NSTEPS, pi, run_time, abs(ref_pi - pi) end program -- GitLab