Polynomial long division: Difference between revisions
Content deleted Content added
Remove redundant branch from pseudocode |
→{{header|Ursala}}: added zkl |
||
Line 1,929: | Line 1,929: | ||
<-2.700000e+01,-9.000000e+00,1.000000e+00>, |
<-2.700000e+01,-9.000000e+00,1.000000e+00>, |
||
<-1.230000e+02>)</pre> |
<-1.230000e+02>)</pre> |
||
=={{header|zkl}}== |
|||
<lang zkl>fcn polyLongDivision(a,b){ // (a0 + a1x + a2x^2 + a3x^3 ...) |
|||
_assert_(degree(b)>=0,"degree(%s)%d < 0".fmt(b,degree(b))); |
|||
q:=List.createLong(a.len(),0.0); |
|||
while((ad:=degree(a)) >= (bd:=degree(b))){ |
|||
z,d,m := ad-bd, List.createLong(z,0.0).extend(b), a[ad]/b[bd];; |
|||
q[z]=m; |
|||
d,a = d.apply('*(m)), a.zipWith('-,d); |
|||
} |
|||
return(q,a); // may have trailing zero elements |
|||
} |
|||
fcn degree(v){ // -1,0,..len(v)-1, -1 if v==0 |
|||
v.len() - v.copy().reverse().filter1n('!=(0)) - 1; |
|||
} |
|||
fcn polyString(terms){ // (a0,a1,a2...)-->"a0 + a1x + a2x^2 ..." |
|||
str:=[0..].zipWith('wrap(n,a){ if(a) "+ %sx^%s ".fmt(a,n) else "" },terms) |
|||
.sink(String).walk() |
|||
.replace(" 1x"," x").replace("x^0 "," ").replace("x^1 ","x ") |
|||
.replace("+ -", "- "); |
|||
if(str[0]=="+") str[1,*]; // leave leading space |
|||
else String("-",str[2,*]); |
|||
}</lang> |
|||
<lang zkl>q,r:=polyLongDivision(T(-42.0, 0.0, -12.0, 1.0),T(-3.0, 1.0)); |
|||
println("Quotient = ",polyString(q)); |
|||
println("Remainder = ",polyString(r));</lang> |
|||
{{out}} |
|||
<pre> |
|||
Quotient = -27 - 9x + x^2 |
|||
Remainder = -123 |
|||
</pre> |