diff --git a/gallery/example4.pdf b/gallery/example4.pdf index 12ac42b..ff65dec 100644 Binary files a/gallery/example4.pdf and b/gallery/example4.pdf differ diff --git a/gallery/example4.typ b/gallery/example4.typ index a671a61..079dada 100644 --- a/gallery/example4.typ +++ b/gallery/example4.typ @@ -32,3 +32,16 @@ $ [quotient: #poly.display(div.quotient)], [rest: #poly.display(div.rest)], )) + +#let r = poly.poly(6, -11, 6, -1) +#let horner = poly.horner(r, 2) +$ + r = #poly.display(r, var: "lambda") = + (#poly.display(horner.root-factor, var: "lambda")) + (#poly.display(horner.factor, var: "lambda")) +$ + +#(horner.display)() + +#let a = poly.mul(horner.root-factor, horner.factor) +$#poly.display(a, var: "lambda")$ \ No newline at end of file diff --git a/src/poly.typ b/src/poly.typ index 21c23d3..4005d36 100644 --- a/src/poly.typ +++ b/src/poly.typ @@ -38,7 +38,7 @@ return poly(..original.coefs) } -#let display(poly) = { +#let display(poly, var: "x") = { _check(poly) let fractions = (2, 3, 4, 5, 6) @@ -73,7 +73,7 @@ res += str(beautify-frac(calc.abs(coef))) } if poly.deg - i > 0 { - res += "x" + res += var } if poly.deg - i > 1 { res += "^" + str(poly.deg - i) @@ -115,8 +115,22 @@ } #let mul(poly1, f) = { - let coefs = poly1.coefs.map(c => c * f) - return poly(..coefs) + if is-poly(f) { + let coefs = (0,) * (poly1.deg + f.deg + 1) + + for (i, c1) in poly1.coefs.enumerate() { + for (j, c2) in f.coefs.enumerate() { + coefs.at(i + j) += c1 * c2 + } + } + return poly(..coefs) + + } else if type(f) == int or type(f) == float { + let coefs = poly1.coefs.map(c => c * f) + return poly(..coefs) + } else { + panic("Invalid type: f must be a polynomial or a number") + } } #let to-cells(poly) = { @@ -230,4 +244,50 @@ steps: steps, display: make-table ) +} + +#let horner(poly1, root) = { + let coefs = poly1.coefs.rev() + let initial = ("", ..coefs) + let mid = ("", $arrow.b$) + let result = (root, coefs.first()) + + for i in range(coefs.len() - 1) { + let a = result.at(i+1) * root + mid.push(a) + let b = initial.at(i+2) + a + result.push(b) + } + + let make-table() = { + let split(cells) = { + let cells2 = () + cells2.push([$#cells.first()$]) + cells2.push(table.vline()) + for c in cells.slice(1,cells.len()-1) { + cells2.push([$#c$]) + } + cells2.push(table.vline()) + cells2.push([$#cells.last()$]) + return cells2 + } + + table( + columns: coefs.len() + 1, + align: right, + stroke: none, + ..split(initial), + ..mid.map(c => $#c$), + table.hline(), + ..result.map(c => $#c$) + ) + } + + return ( + poly: poly1, + root: root, + root-factor: poly(-root, 1), + factor: poly(..result.rev().slice(1, -1)), + display: make-table + ) } \ No newline at end of file