1

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.

11
  • 1
    In 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. Commented Aug 26, 2021 at 17:14
  • 1
    You don't need cos(pi/2.0_dp) instead of cos(pi/2) because pi is double precision so the 2 will be converted to double precision as part of the calculation. It doesn't hurt, though. Commented Aug 26, 2021 at 17:24
  • 2
    There's certainly no need to delete this question, and it's your choice. Beware, however, that this question does get asked a lot, so there may be some risk of downvotes. Commented Aug 26, 2021 at 17:24
  • 1
    Thanks for clearing it up... I did just try without _dp in cos, and it works fine. I quickly changed pi in my main code, and it works now! I have been on this for weeks, did go through many of those repeated posts, but missed this important point to put _dp inside argument for tan. I will keep the question undeleted, might still help someone, if they miss it like me from earlier posts. Thank you so much for all your input. Commented Aug 26, 2021 at 17:33
  • 1
    @ZeroTwo, use Real(dp), parameter:: pi=4.0d0*atan(1.0d0) Commented Aug 30, 2021 at 2:10

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.