Lily
Lily

Reputation: 13

Square Root program using Difference Equations

I made a program using difference equation initial conditions for each number, but as you can see the code didn't give me satisfying results, plus it took more loops than it's supposed to, it should be two runs for each number maximum. The square root of 5 = 2.23 after 2 loops.

N=4;
S=[5 10 15 27 40]; %root squared numbers input variables 
y1=[2 3 4 5 6]; %1st Initial conditions
for  i=0:1:1
for  n=1:1:3
y1(n)=0.5*(y1(i+1)+(S(n)./y1(i+1)))
end
end

Results on command window:

y1 =
    2.2500    3.0000    4.0000    5.0000    6.0000
y1 =
    2.2500    3.3472    4.0000    5.0000    6.0000
y1 =
    2.2500    3.3472    4.4583    5.0000    6.0000
y1 =
    2.4205    3.3472    4.4583    5.0000    6.0000
y1 =
    2.4205    3.1674    4.4583    5.0000    6.0000
y1 =
    2.4205    3.1674    3.9516    5.0000    6.0000

Upvotes: 1

Views: 72

Answers (1)

John Bofarull Guix
John Bofarull Guix

Reputation: 820

The inner loop does not address all elements of y1. Try this instead:

format long

S=[5 10 15 27 40]; 
y=[2 3 4 5 6]; 

% y=2*x*x'

for n=1:5
    for i=1:numel(S)
        y(i)=0.5*(y(i)+(S(i)./y(i)));
    end
    disp(y)
end

The closing line is

y =

   2.236067977499790   3.162277660168379   3.872983346207417

   5.196152422706632   6.324555320336758

The exact solution being

 S.^.5
 =
   2.236067977499790   3.162277660168380   3.872983346207417

   5.196152422706632   6.324555320336759

Now your 2 loops reach the expected values much faster.

Upvotes: 3

Related Questions