Polynomial long division: Difference between revisions
Content added Content deleted
m (can / could, since anyway a single-pos shift makes it simpler/clearer than using subarrays (and indexes) instead) |
(octave) |
||
Line 396: | Line 396: | ||
r = -23.*x + -14. |
r = -23.*x + -14. |
||
</pre> |
</pre> |
||
=={{header|Octave}}== |
|||
Octave has already facilities to divide two polynomials; and the reason to adopt the convention of keeping the higher power coefficient first, is to make the code compatible with builtin functions: we can use <tt>polyout</tt> to output the result. |
|||
<lang octave>function [q, r] = poly_long_div(n, d) |
|||
gd = length(d); |
|||
pv = zeros(1, length(n)); |
|||
pv(1:gd) = d; |
|||
if ( length(n) >= gd ) |
|||
q = []; |
|||
while ( length(n) >= gd ) |
|||
q = [q, n(1)/pv(1)]; |
|||
n = n - pv .* (n(1)/pv(1)); |
|||
n = shift(n, -1); % |
|||
tn = n(1:length(n)-1); % eat the higher power term |
|||
n = tn; % |
|||
tp = pv(1:length(pv)-1); |
|||
pv = tp; % make pv the same length of n |
|||
endwhile |
|||
r = n; |
|||
else |
|||
q = [0]; |
|||
r = n; |
|||
endif |
|||
endfunction |
|||
[q, r] = poly_long_div([1,-12,0,-42], [1,-3]); |
|||
polyout(q, 'x'); |
|||
polyout(r, 'x'); |
|||
disp(""); |
|||
[q, r] = poly_long_div([1,-12,0,-42], [1,1,-3]); |
|||
polyout(q, 'x'); |
|||
polyout(r, 'x'); |
|||
disp(""); |
|||
[q, r] = poly_long_div([1,3,2], [1,1]); |
|||
polyout(q, 'x'); |
|||
polyout(r, 'x'); |
|||
disp(""); |
|||
[q, r] = poly_long_div([1,3], [1,-12,0,-42]); |
|||
polyout(q, 'x'); |
|||
polyout(r, 'x');</lang> |
|||
=={{header|Python}}== |
=={{header|Python}}== |