简体   繁体   中英

Error in code of bisection method

I used a code for bisection method, which supposed to be working, unfortunately it´s not and I do not know what is the problem. This code also includes user defined precision and a counter for number of iterations. The error I´m getting is for the last line in the code: Undefined function or variable 'c'.

a=-5;
b=0;
tol = input('What precision would you like? ','s')
fa=a^3-20+exp(a);
fb=b^3-20+exp(b);
counter=1
while abs(b-a) > tol
  c=(a+b)/2;
  fx = c*c-2;
  if fa*fc<0
      b=c;
      fb=fc;
  elseif fb*fc<0
      a=c;
      fa=fc;
  else
      break
  end
  fprintf('Just finished iteration #%d\n', counter);
  counter=counter+1;
end
x=c;

Since you are loading the input as a string (with the s argument), the tol variable will be a character array. For example, entering 1E-10 for the current script will define tol as a character array, and the first evaluation of the expression in the while construct will be equivalent to

>> abs(0 - -5) > '1E-10'
ans =
     0     0     0     0     0

So the while loop is completely skipped.

So either remove s from the input call, or wrap the input call in a str2double .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM