Fortran program giving a wrong output?

AboAmmar

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.

AboAmmar

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related