1

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
1
  • 1
    Welcome to stackoverflow, please edit your question to include a minimal reproducible example. It's unclear what you expect as outputs, what would be a "satisfying" / expected result? Why do you assert that? Have you tried stepping through your code to find the specific point where the output diverges from your expectations? Keep in mind that we have zero contextual information other than what you include in the question for what you're trying to achieve Commented Feb 20, 2023 at 14:10

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Comment: The code in the question uses n that cannot go above amount elements in initial condition vector. Now n is the amount of loops so when using same approach for different approximation n can be increased to whatever satisfies error thresholds.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.