0

I want to use an OR statement in my while loop so that the loop terminates whenever either of the two conditions aren't satisfied.

The conditions: (1) i must be less or equal to nmax, and (2) absolute value of R(i,i)-R(i-1,i-1) is less than specified delta

Here's my code (everything seems to work fine except for the while condition as the function executes until nmax is reached every time):

    function [R] = romberg(f,a,b,delta,nmax)
    R=zeros(nmax,nmax);
    R(1,1)=(f(a)+f(b))*(b-a)/2;
    i=2;
    while i<nmax || abs(R(i,i)-R(i-1,i-1))<delta
        m=2^(i-1);
        R(i,1)=trapez(f,a,b,m);
        for j=2:i
            R(i,j)=R(i,j-1)+(R(i,j-1)-R(i-1,j-1))/(4^j-1);
        end
        i=i+1;
    end
    R
3
  • You want an and, &&, not an or, || in the while loop definition. You want to keep going as long as i<nmax AND abs(R(i,i)-R(i-1,i-1))<delta. Instead, your code will keep going as long as either i<nmax OR abs(R(i,i)-R(i-1,i-1))<delta. Commented Apr 15, 2014 at 4:17
  • I had thought the same, and tried that. However, when I use && the loop terminates after 1 iteration Commented Apr 15, 2014 at 4:19
  • I think it should be abs(R(i,i)-R(i-1,i-1))>delta assuming that it is looping while the error or something is bigger than delta. Commented Apr 15, 2014 at 4:29

1 Answer 1

1

Try this. There were a few issues with the abs(R(i,i)-R(i-1,i-1)) condition for the while loop.

function [R] = romberg(f,a,b,delta,nmax)
    R=zeros(nmax,nmax);
    R(1,1)=(f(a)+f(b))*(b-a)/2;
    i=2;
    E=2*delta;
    while i<nmax && E>delta
        m=2^(i-1);
        R(i,1)=trapez(f,a,b,m);
        for j=2:i
            R(i,j)=R(i,j-1)+(R(i,j-1)-R(i-1,j-1))/(4^j-1);
        end        
        E=abs(R(i,i)-R(i-1,i-1));
        i=i+1;
    end
Sign up to request clarification or add additional context in comments.

Comments

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.