0
votes

I have 2 functions here:

function y=f(x)
    y=(x*%e^x)-cos(x);
endfunction

function c=regulafalsi(f, x0, x1, tol)
    i=1;
    n(1)=100;
    if f(x0)*f(x1) < 0
        a(1)=x0;
        b(1)=x1;
        c(1)=a(1)-f(a(1))*(b(1)-a(1))/(f(b(1))-f(a(1)));
        printf('i.\t\t a\t\t c\t\t b\t\t f(c)\t  Galat  \n');
        printf('%2d \t %11.4f \t %11.4f \t %11.4f \t %11.4f \n',i,a(i),c(i),b(i),f(c(i)));
        while abs(n(i))>=tol,
            if f(a(i))*f(c(i))< 0
                a(i+1)=a(i);
                b(i+1)=c(i);
            end
            if f(a(i))*f(c(i))> 0
                a(i+1)=c(i);
                b(i+1)=b(i);
            end      
            c(i+1)=a(i+1)-f(a(i+1))*(b(i+1)-a(i+1))/(f(b(i+1))-f(a(i+1)));
            n(i+1)=abs((c(i+1)-c(i))/(c(i+1)));
            printf('%2d \t %11.4f \t %11.4f \t %11.4f \t %11.4f \t %7.4f \n',i+1,a(i+1),c(i+1),b(i+1),f(c(i+1)),n(i+1));
            i=i+1;
        end
    else
        printf(' ');
    end
endfunction

How to plot those function? I tried plot(y,c) not working.

1

1 Answers

0
votes

You have two Scilab functions but only the first of them represents a mathematical function that could be plotted. The second one is a root-finding procedure which outputs some numerical data; it's not meant to be fed into plot command.

To plot function f, you can do the following (e.g., at the end of your script, or in command window)

x = linspace(0,1)
plot(x,f(x))

plot

Here 0, 1 are the endpoints of the interval on which to plot. The linspace command creates an array of numbers distributed over that interval, which is fed into f and then the result into plot.

In order for this to work, you will need to adjust your formula for f slightly:

function y=f(x)
    y=(x.*exp(x))-cos(x);
endfunction

The dot before * indicates the multiplication is to be done component wise. This allows this function to process arrays of numbers at once.

Your root-finding function (the method of false position, apparently) works fine. For example, executed with

 regulafalsi(f,0,1,0.01)

it returns

i.         a               c               b               f(c)       Galat  
 1        0.0000          0.3147          1.0000         -0.5199 
 2        0.3147          0.4467          1.0000         -0.2035      0.2956 
 3        0.4467          0.4940          1.0000         -0.0708      0.0957 
 4        0.4940          0.5099          1.0000         -0.0236      0.0312 
 5        0.5099          0.5152          1.0000         -0.0078      0.0102 
 6        0.5152          0.5169          1.0000         -0.0025      0.0033 

The root around 0.516 has been found.