Roots of a function: Difference between revisions

Content added Content deleted
m (sorting GNU Octave by G instead of by O)
m (oct...)
Line 286: Line 286:
END DO</lang>
END DO</lang>


=={{header|GNU Octave}}==

If the equation is a polynomial, we can put the coefficients in a vector and use ''roots'':

<lang matlab>a = [ 1, -3, 2, 0 ];
r = roots(a);
% let's print it
for i = 1:3
n = polyval(a, r(i));
printf("x%d = %f (%f", i, r(i), n);
if (n != 0.0)
printf(" not");
endif
printf(" exact)\n");
endfor</lang>

Otherwise we can program our (simple) method:

{{trans|Python}}
<lang matlab>function y = f(x)
y = x.^3 -3.*x.^2 + 2.*x;
endfunction

step = 0.001;
tol = 10 .* eps;
start = -1;
stop = 3;
se = sign(f(start));

x = start;
while (x <= stop)
v = f(x);
if ( (v < tol) && (v > -tol) )
printf("root at %f\n", x);
elseif ( sign(v) != se )
printf("root near %f\n", x);
endif
se = sign(v);
x = x + step;
endwhile</lang>


=={{header|J}}==
=={{header|J}}==
Line 406: Line 366:
Out[6]= x==0||x==1||x==2
Out[6]= x==0||x==1||x==2
(note that this doesn't yield a "solution" but a different expression that expresses the same thing as the original)
(note that this doesn't yield a "solution" but a different expression that expresses the same thing as the original)

=={{header|Octave}}==

If the equation is a polynomial, we can put the coefficients in a vector and use ''roots'':

<lang matlab>a = [ 1, -3, 2, 0 ];
r = roots(a);
% let's print it
for i = 1:3
n = polyval(a, r(i));
printf("x%d = %f (%f", i, r(i), n);
if (n != 0.0)
printf(" not");
endif
printf(" exact)\n");
endfor</lang>

Otherwise we can program our (simple) method:

{{trans|Python}}
<lang matlab>function y = f(x)
y = x.^3 -3.*x.^2 + 2.*x;
endfunction

step = 0.001;
tol = 10 .* eps;
start = -1;
stop = 3;
se = sign(f(start));

x = start;
while (x <= stop)
v = f(x);
if ( (v < tol) && (v > -tol) )
printf("root at %f\n", x);
elseif ( sign(v) != se )
printf("root near %f\n", x);
endif
se = sign(v);
x = x + step;
endwhile</lang>



=={{header|Perl}}==
=={{header|Perl}}==