Anonymous user
Roots of a function: Difference between revisions
m
sorting GNU Octave by G instead of by O
(gnu octave (using matlab hl, which has some problem indeed)) |
m (sorting GNU Octave by G instead of by O) |
||
Line 285:
i = i + 1
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}}==
Line 365 ⟶ 406:
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)
▲=={{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|Perl}}==
|