Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't input value in f(x) in this Fortran code?

Tags:

fortran

    program prob_1
    implicit real*8(a-h, o-z)
    f(x) = x**2-cos(x)
    df(x) = 2*x+sin(x)
    x0 = 0, x1 = 1
    do i = 1, 3
        if (f((x0+x1)/2) < 0)
            x0 = (x0+x1)/2
        else
            x1 = (x0+x1)/2
    end do
    print *,"x = ", x
end program

I'm just starting to use Fortran 90. Now I'm using Code::blocks but I don't know exactly which line the error exists on.

I guess the problem is f((x0+x1)/2) < 0 but don't know actually what is the real error. what's problem is here?

like image 278
권태형 Avatar asked Mar 04 '26 23:03

권태형


2 Answers

Be advised that statement functions, the function definitions the OP uses, are obsolescent.

B.3.4 Statement functions

  1. Statement functions are subject to a number of non intuitive restrictions and are a potential source of error because their syntax is easily confused with that of an assignment statement.
  2. The internal function is a more generalized form of the statement function and completely supersedes it.

source: F2018 Standard

Also the notation REAL*8 or anything of that form has never been part of any Fortran standard (see here):

I would suggest to rewrite the code as:

program prob_1
    implicit none
    double precision :: x1,x0
    integer          :: i
    x0 = 0; x1 = 1
    do i = 1, 3
        if (f((x0+x1)/2.0D0) < 0) then
            x0 = (x0+x1)/2.0D0
        else
            x1 = (x0+x1)/2.0D0
        endif
    end do
    print *,"x = ", (x0+x1)/2.0D0
contains
    function f(x)
      double precision, intent(in) :: x
      double precision             :: f
      f = x**2-cos(x)
    end function f
   function df(x)
      double precision, intent(in) :: x
      double precision             :: df
      df = 2.0D0*x+sin(x)
    end function df
end program
like image 108
kvantour Avatar answered Mar 06 '26 17:03

kvantour


If you change your program as follows then it will compile:

program prob_1
    implicit real*8(a-h, o-z)
    f(x) = x**2-cos(x)
    df(x) = 2*x+sin(x)
    x0 = 0; x1 = 1
    do i = 1, 3
        if (f((x0+x1)/2) < 0) then
            x0 = (x0+x1)/2
        else
            x1 = (x0+x1)/2
        endif
    end do
    print *,"x = ", x
end program

As mentionned in the comments, you have to add the semicolon ; to separate statements in one line and you have to add the then as well as endif to your if condition.

Hope it helps.

like image 38
CKE Avatar answered Mar 06 '26 17:03

CKE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!