문제

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
도움이 되었습니까?

해결책

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
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top