# Can't figure out what's wrong with my code

15 ビュー (過去 30 日間)
Kevin Krause 2015 年 11 月 1 日
Edited: Mischa Kim 2017 年 11 月 6 日
One of the main problems is that there will never be a sign change on the interval so it'll always execute the first part of the if statement. I commented out the err>errtol part for testing. I don't know what i'm doing wrong for calculating using the bisection method. I have to use while loops.
% A scale is made with two springs, and when an object is attached to the
% two springs, the springs stretch and the ring at the end of the two
% springs is displaced downwards a distance x.
%
% The relationship between the weight of the object and the distance x is:
% W=(2k/l)(l-lo)(b+x)
% The initial spring length
% lo = sqrt(a^2+b^2)
% The stretched spring length
% l = sqrt(a^2+(b+x)^2)
% for the given scale a=8.0 in. b=5.0 m. and the spring constant k=16.0 lb/in.
% b=5.0 m.=196.85 in.
% Trying to find the deflection x.
%
% Have the user input lower and upper values of the starting
% interval (xl, xu), as well as the weight of the object
% Initialize the error tolerance (errtol)
% and the maximum number of iterations (maxiter)
%
% Check the interval to see if there's a sign change
%
% while (iterations < maxiter) and (err > errtol)
% Calculate midpoint of the interval xr=(xl+xu)/2
% Calculate error estimate (err)
% Evaluate the function at the midpoint f(xr)
% If the sign of f(xr) is equal to the sign of f(xl)
% if f(xr)*f(xu)>0
% then xr becomes the new xl.
% else xr becomes the new xu.
% end while loop
%
% If err <= errtol
% then solution found, output result
W = input('\nWhat is the weight of the object attached to the ring in pounds (lb)? ');
xl = input('\nWhat is the lower initial bracket estimate in inches? '); %always 0
xu = input('\nWhat is the upper initial bracket estimate in inches? '); %always 10
a = 8.0;
b = 5.0 ;
lo = sqrt(a^2+b^2);
k = 16.0;
errtol = 0.005;
xr = (xl+xu)/2;
maxiter = 10;
iterations = 0;
f = @(x) (2*k/(sqrt(a^2+(b+x)^2)))*((sqrt(a^2+(b+x)^2))-lo)*(b+x);
err = abs((xu-xl)/xu);
xrold = abs((xu-xl)/xu);
while (iterations<maxiter) %|| (err>errtol)
iterations=iterations+1;
xr=(xl+xu)/2;
err = abs((xr-xrold)/xr)*100;
if f(xr)*f(xl)>0
xu = xr;
else
xl = xr;
end
xrold = xr;
end

#### 2 件のコメント

Image Analyst 2015 年 11 月 1 日
What values for W, xl, and xu did you enter?
Cleysa Medina 2017 年 11 月 6 日
How does the weight affect the xr?

サインイン to comment.

### 件の回答 (1)

Mischa Kim 2017 年 11 月 6 日

Kevin, I see two problems with your algorithm/function f(x):
if f(xr)*f(xl)>0
needs to be
if f(xr)*f(xl)<0
and the function f(x) does not (I believe) have any roots for positive x and for the set of parameters you chose. In other words, the starting xl needs to be negative for the algorithm to converge to a root. According to your comments, xl is always 0.

#### 0 件のコメント

サインイン to comment.

サインイン してこの質問に回答します。