Fortra 90 : Error in my program of bisection method

  • Thread starter fluidistic
  • Start date
  • #1
fluidistic
Gold Member
3,654
100

Main Question or Discussion Point

Hello,
I'm having trouble with a very simple program. I want it to approximate a square root of a number R. So here is my program :
Program biseccion
implicit none

Real(8) :: R,a,b,Tol,d
Integer :: i

Write(*,*)'Enter R, a, b and Tol'
Read(*,*)R,a,b,Tol

i=0
d=(a+b)/2.

Do while (abs(f(d))>Tol)
d=(a+b)/2.
If (f(a)*f(d)>0) Then
a=d
Else
b=d
end if
i=i+1
Write(*,*)i,d,f(d)
End Do

Contains
Real Function f(x)
implicit none
Real(8) :: x, R
f=x**2-R
end function

end program
For example, if you enter R as 3, a as 1, b as 2 and Tol as 0.001, it should return " d " as the square root of we were looking for, "i" as the number of steps to reach it, and "f(d)" as the real value of the function f (obviously close to Tol). But it doesn't work. I've tried to find an error, but I don't see any. Maybe there is a problem in the function f.... but I'm not sure.
I'd be grateful if you could run the program to see what happens, or if you any error. Thanks a lot.
 

Answers and Replies

  • #2
Borek
Mentor
28,328
2,717
I believe the reason is obvious, and should be pretty easy to identify just by looking at the output. Try Write(*,*)i,d,a,b,f(d).

And please don't call f(x) each time. Think about efficiency.
 
  • #3
fluidistic
Gold Member
3,654
100
I just tried "Write(*,*)i,d,a,b,f(d)", in one example a wasn't changing and b got b^2, b^4, etc. In another example I got about 3000 iterations were a and b didn't change, and so did d. And I always considered a small interval containing the root. I still don't see the error. Now I guess it's in the do while.
 
  • #4
alphysicist
Homework Helper
2,238
1
Hi fluidistic,

By declaring R in your function, you have set up a new variable R that is specific to that function, and therefore you have made the function unable to access the R in the main program.

If you don't declare it in the function I believe it will work properly.
 
  • #5
fluidistic
Gold Member
3,654
100
Thanks once again alphysicist. It now works as it should. The error wasn't obvious for me.
 

Related Threads for: Fortra 90 : Error in my program of bisection method

Replies
17
Views
19K
  • Last Post
Replies
4
Views
3K
Replies
3
Views
11K
Replies
11
Views
680
Replies
7
Views
1K
Replies
7
Views
686
Replies
19
Views
3K
Replies
8
Views
4K
Top