COMPGROUPS.NET | Search | Post Question | Groups | Stream | About | Register

### Roots - Bisection method

• Email
• Follow

```Hi all,

I have created a simple sine plot and I wish to implement the bisection method to yield all the intersection points along the x-axis (i.e. where y = 0);  however, my code is simply bisecting the whole range and splitting it instead of checking the range at intervals.  If run, the code will work, but to only converge at one point.

I would appreciate any help!!

Many thanks!

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

clc;

fo = 10;
Fs = 1000;
Ts = 1/Fs;
i = 0:Ts:1-Ts;
n = length(i);
SI = 2*sin(2*pi*fo*i);

yy = 0;

plot(i,SI,i,yy);

I = @(x) 2*sin(2*pi*fo*x);

a = 0;
b = 0.999;
TOL = 0.01;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

NumIters = 0; % initialize iteration counter
MaxIters = 10;

for x = a:0.001:b

fa = feval(I,a);
fb = feval(I,b);

sfa = sign(fa);
sfb = sign(fb);

if (sfa*sfb > 0)
% this doesn't satisfy the sufficiency condition for existence of
% a root
error('The bisection method requires f(a)f(b) < 0 ');
end

% bisection loop
% disp(sprintf('\t iterate \t\t interval \t\t\t\t\t p'));
while (NumIters <= MaxIters)
% use midpoint as the iterate
p = (a+b)/2;
fp = feval(I,p);
sfp = sign(fp);

% display some data to the screen
disp (sprintf ('\t %3d \t (%.10f,%.10f) \t %.10f', NumIters, a, b, p ) )

if ( (b-a)<2*TOL | fp == 0)
x = p;
return % terminate this function early
elseif (sfa*sfp < 0)
b = p;
else
a = p;
end

NumIters = NumIters + 1;
end

% if this while loop terminates before returning the root
disp(' max number of iterations reached ... ')
x = a;

end
```
 0

See related articles to this posting

```You're going about this the wrong way. See what I've done here and edit accordingly.

clc;

fo = 10;
Fs = 1000;
Ts = 1/Fs;
i = 0:Ts:1-Ts;
n = length(i);
SI = 2*sin(2*pi*fo*i);

yy = 0;

plot(i,SI,i,yy);

I = @(x) 2*sin(2*pi*fo*x);

TOL = 0.01;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

MaxIters = 10;

for a = 0:.01:1

% intervals tested are 0-.03, .01-.04, .02-.05 ...1-1.03
b = a + .03;

fa = feval(I,a);
fb = feval(I,b);

sfa = sign(fa);
sfb = sign(fb);

if (sfa*sfb > 0)
continue
end

disp(['Interval: [', num2str(a),', ',num2str(b),']'])

% bisection loop
% disp(sprintf('\t iterate \t\t interval \t\t\t\t\t p'));
an = a;
bn = b;

NumIters = 0; % initialize iteration counter

while (NumIters <= MaxIters)
% use midpoint as the iterate
p = (an+bn)/2;
fp = feval(I,p);
sfp = sign(fp);

% display some data to the screen
disp (sprintf ('\t %3d \t (%.10f,%.10f) \t %.10f', NumIters, a, b, p ) )

fa = feval(I,an);
fb = feval(I,bn);

sfa = sign(fa);
sfb = sign(fb);

if ( (b-a)<2*TOL | fp == 0)
x = p;
break % terminate this function early
elseif (sfa*sfp < 0)
bn = p;
else
an = p;
end

NumIters = NumIters + 1;
end

% if this while loop terminates before returning the root
disp(' max number of iterations reached ... ')
x = p;

end
```
 0

```BTW, my intervals overlap each other, so you will see a lot of duplicate roots.
To change this, edit the for loop index into something else.

For example, to overcome overlapping, you can use the following lines:

a = 0:0.03:1
b = a + .03;
```
 0

```Husam,

Thank you very much for your repl(ies).

I have implemented what you suggested and indeed the code outputs periodic roots.  However, I am trying to plot these over my original signal SI by using the following

if ( (bn-an)<2*TOL | fp == 0)
x = p
hold on;
plot(i,SI,i,x)

etc..

However, I am not getting what I require which is single points at periodic intervals.  Have you any suggestions?
```
 0

```Yes.
clc;

fo = 10;
Fs = 1000;
Ts = 1/Fs;
i = 0:Ts:1-Ts;
n = length(i);
SI = 2*sin(2*pi*fo*i);

yy = 0;

plot(i,SI,i,yy);

I = @(x) 2*sin(2*pi*fo*x);

TOL = 0.01;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

MaxIters = 10;

X = [];

for a = 0:.03:.9

% intervals tested are 0-.03, .01-.04, .02-.05 ...1-1.03
b = a + .03;

fa = feval(I,a);
fb = feval(I,b);

sfa = sign(fa);
sfb = sign(fb);

if (sfa*sfb > 0)
continue
end

disp(['Interval: [', num2str(a),', ',num2str(b),']'])

% bisection loop
% disp(sprintf('\t iterate \t\t interval \t\t\t\t\t p'));
an = a;
bn = b;

NumIters = 0; % initialize iteration counter

while (NumIters <= MaxIters)
% use midpoint as the iterate
p = (an+bn)/2;
fp = feval(I,p);
sfp = sign(fp);

% display some data to the screen
disp (sprintf ('\t %3d \t (%.10f,%.10f) \t %.10f', NumIters, a, b, p ) )

fa = feval(I,an);
fb = feval(I,bn);

sfa = sign(fa);
sfb = sign(fb);

if ( (b-a)<2*TOL | fp == 0)
x = p;
break % terminate this function early
elseif (sfa*sfp < 0)
bn = p;
else
an = p;
end

NumIters = NumIters + 1;
end

% if this while loop terminates before returning the root
disp(' max number of iterations reached ... ')
x = p;
X = [X;x];

end
hold on
plot(X,zeros(size(X)),'*')
```
 0

```Many thanks for your help Hasam, objectives achieved. :)
```
 0

5 Replies
337 Views

Similar Articles

12/8/2013 9:28:02 PM
page loaded in 30866 ms. (0)

Similar Artilces:

todays method
.... i am looking for a button with a selectable field that can be changed if you select another value. not a dropdown menu but a button with up and down controls but arrow up, arrow down, which when pressed change the value in the field. when you press the button you get the selected value. .... any help -- Sometimes I'm in a good mood. Sometimes I'm in a bad mood. When all my moods have cum to pass i hope they bury me upside down so the world can kiss me porcelain, white, Irish bottom. On Sat, 12 May 2007 18:18:13 +0100, beelzibub @ bawston school for idiots <comprehensivece

protected method
Hello.... May I know how to use a protected method? Here's my code: String[] info = ct.getExtraInfo(); getExtraInfo is a protected method . . . IveCal wrote: > Hello.... > May I know how to use a protected method? > > Here's my code: > > String[] info = ct.getExtraInfo(); > > getExtraInfo is a protected method . . . You need to read a bit about the various access modifiers for methods and members. If the person who wrote, ct.getExtraInfo() things it only makes sense for subclasses then you might consider making a subclass for whatever Ct is: class MyCT extends CT { public void getEXtraInfo() { super.ppp(); } } .... ct = new MyCt(); But you also might ask the designers of the class what the problem with calling getExtraInfo() is and why it isn't public. Also, you're screwed (or properly controlled) if MyCT's come from a factory. -Paul > If the person who wrote, ct.getExtraInfo() things it only makes sense > for subclasses A particular class' protected methods are also accessible by classes in same package as particular class (even when those classes do not subclass). Putting this info

Method chaining
A frequently missed feature is the ability to chain method calls: x = [] x.append(1).append(2).append(3).reverse().append(4) => x now equals [3, 2, 1, 4] This doesn't work with lists, as the methods return None rather than self. The class needs to be designed with method chaining in mind before it will work, and most Python classes follow the lead of built-ins like list and have mutator methods return None rather than self. Here's a proof-of-concept recipe to adapt any object so that it can be used for chaining method calls: class chained: def __init__(self, obj): self.obj = obj def __repr__(self): return repr(self.obj) def __getattr__(self, name): obj = getattr(self.obj, name) if callable(obj): def selfie(*args, **kw): # Call the method just for side-effects, return self. _ = obj(*args, **kw) return self return selfie else: return obj chained([]).append(1).append(2).append(3).reverse().append(4) => returns [3, 2, 1, 4] Tested, and works, in CPython 2.4 through 2.7, 3.2 and 3.3, Jython

Run Method
I'm kind of confused here - class A extends Thread { public void run() { synchronized (...) { } } } what may be the use of having a synchronized block in a thread's run method ? I was under the impression, that only one thread will access the run method i,e the current running thread. -t You can have multiple A's all running at the same time, synchronizing on a shared object. That way only one of all A threads will execute the code in the block at the same time. A use for this might be where multiple threads append to the same file from that run method. This way it is assured that the written data will not end mixed up. Bart

OpenRecordset method
I am developing a program in Access 2000. I couldn't make OpenRecordset method work right. It's working when I opened a simple SQL query below in OpenRecordset. ..... Dim dbs As Database, rst As Recordset Set dbs = CurrentDb Set rst = dbs.OpenRecordset("Select * from ATest") ..... But when I tried to use the value of Text Box object in a SQL query's criteria, it warned me "Run-time error '3061', Too few parameters. Expected 4". The SQL query is as below: Select * from ATest Where Date >[Forms]![myForm].txtDate Thanks for your time and help. The openrecordset method expects a string as the SQL, so it interprets [Forms]![myform ... as just part of that string and doesn't get the value of the textbox. To get the value of the textbox in there, you have to do this: sest rst= dbs.OpenRecordset("Select * from ATest Where Date > " & [Forms]![myForm].txtDate) hope that helps -John "Sunnyrain" <southwud@hotmail.com> wrote in message news:1134341976.932793.210190@g14g2000cwa.googlegroups.com... >I am developing a program in Access 2000. I couldn't make OpenRecordset > method work right