I am using the following code to calculate cos for pi/2 in Fortran.
program precision_Fortran IMPLICIT NONE !!integer, parameter :: dp = kind(1.0d0) !!Gives same result as line below integer, parameter :: dp = selected_real_kind(15, 307) Real(dp), parameter:: pi=4.0*atan(1.0) Real(dp) :: angle angle = cos(pi/2.0) write(*,*)'pi = ', pi write(*,*)'angle = ', angle end program precision_Fortran I compiled using gfortran and ftn95. From both, the output is
pi = 3.1415927410125732 angle = -4.3711390001862412E-008 How do I get a better precision for angle here? For instance in C++ I see it in order of E-18, for all declaration using double.
Please let me know if more information is needed to explain it better.
Extra : The main code I am using, with physical equations having trigonometric terms, is having precision issues, and am not entirely sure, but am suspecting it's because of this. So, want to check if above could be improved somehow. Not expert with Fortran so struggling to figure this out.
pi=4.0*atan(1.0)everything on the right-hand side is in default real, so won't be as precise as if done in double precision.cos(pi/2.0_dp)instead ofcos(pi/2)becausepiis double precision so the2will be converted to double precision as part of the calculation. It doesn't hurt, though.Real(dp), parameter:: pi=4.0d0*atan(1.0d0)