0

I'm new to Fortran, so forgive me if I'm doing something stupid in the following code:

program test2
    implicit none

    ! Variable declaration
    integer :: i, n
    real    :: s

    ! Initialization
    n = 1e+9
    s = 0.0

    do i=1,n
        s = s + real(i)
        s = s + sqrt(s)
    end do

    print *, s

end program test2

This small program outputs: 1.8014399E+16 and I expect it to give 1.0000000010000024E+18. I use the GNU Fortran compiler on a Windows 10 machine.

5
  • I usually run long simulations involving many matrices. Matrix multiplications, concatenations, reshaping, indexing, FFTs, random number generations, MAX, mean, powers, complex numbers, etc are the typical operations I use and I read that Modern Fortran comes with heavy support for matrix operations with super high speeds. Commented Nov 30, 2016 at 23:01
  • 2
    If you change real ::s to double precision :: s do you get the answer you expect? Commented Nov 30, 2016 at 23:20
  • Wow, that is right. But I tried many other things like kind = 16, real*16, etc, but all didn't work, do you know why? Commented Nov 30, 2016 at 23:23
  • @francescalus -- Please elaborate your comment into an answer. Commented Nov 30, 2016 at 23:33
  • WRITE ( * , * ) 'SIZEOF(s)=', SIZEOF(s)... You may need REAL(i) to become DBLE(I) on the s = s + line... Commented Dec 2, 2016 at 13:04

1 Answer 1

1

Well, I ended up using the following definition for the double precision variable s. This method has the advantage of being reusable and system independent. Thanks to @francescalus for the comment.

program test2
    implicit none

    ! Variable declaration
    integer, parameter :: dp = kind(0.d0)
    integer  :: i, n
    real(dp) :: s

    ! Initialization
    n = 1e+9
    s = 0.0

    do i=1,n
        s = s + real(i)
        s = s + sqrt(s)
    end do

    print *, s

end program test2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.