Fortra 90 : Error in my program of bisection method

In summary, the programmer was having trouble with a very simple program that involved approximating a square root of a number. They wrote a program that contained an implicit real function and an integer to keep track of how many steps it took to find the square root. They tried to run the program, but it wouldn't work because they had forgotten to declare a variable that was specific to the function. After declaring the variable, the program worked properly.
  • #1
fluidistic
Gold Member
3,961
266
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.
 
Technology news on Phys.org
  • #2
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
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
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
Thanks once again alphysicist. It now works as it should. The error wasn't obvious for me.
 

Similar threads

Replies
1
Views
2K
Replies
12
Views
1K
Replies
4
Views
2K
Replies
11
Views
1K
Replies
25
Views
2K
Replies
11
Views
2K
Back
Top