Roots of a cubic polynomial: Difference between revisions
Content added Content deleted
(julia example) |
(J draft) |
||
Line 22: | Line 22: | ||
=={{header|J}}== |
|||
Using J's [[j:Vocabulary/pdot|polynomial primitive]] for most of the heavy lifting here. Also using J's [[j:Vocabulary/dot|generalized determinant]] to find the characteristic polynomial (first turning each element of the matrix into a polynomial then finding the determinant of the result): |
|||
Implementation: |
|||
<syntaxhighlight lang=J> |
|||
NB. matrix characteristic polynomial |
|||
mcp=: {{ ;pdf/ .ppr y,each -=i.#y }} |
|||
pdf=: -/@,:L:0 NB. polynomial difference |
|||
ppr=: +//.@(*/)L:0 NB. polynomial product |
|||
proots=: 1 {:: p. NB. polynomial roots |
|||
task=: {{ |
|||
poly=. mcp y |
|||
roots=. proots poly |
|||
errors=. poly p."1 0 roots |
|||
lines=. (,:'matrix: '),&.|:&": y |
|||
lp=. 'coefficients: ',":poly |
|||
lr=. 'roots: ',":roots |
|||
le=. 'errors: ',":errors |
|||
lines,lp,lr,:le |
|||
}}</syntaxhighlight> |
|||
Task examples: |
|||
<syntaxhighlight lang=J> |
|||
task 1 _1,0 1 1,:0 0 1 |
|||
matrix: 1 _1 0 |
|||
0 1 1 |
|||
0 0 1 |
|||
coefficients: 1 _3 3 _1 |
|||
roots: 1 1 1 |
|||
errors: 0 0 0 |
|||
task _2 _4 2,_2 1 2,:4 2 5 |
|||
matrix: _2 _4 2 |
|||
_2 1 2 |
|||
4 2 5 |
|||
coefficients: _90 27 4 _1 |
|||
roots: 6 _5 3 |
|||
errors: 0 0 0 |
|||
task 1 _1,0 1 _1,:0 0 1 |
|||
matrix: 1 _1 0 |
|||
0 1 _1 |
|||
0 0 1 |
|||
coefficients: 1 _3 3 _1 |
|||
roots: 1 1 1 |
|||
errors: 0 0 0 |
|||
task 2 0,0 _1,:0 0 _1 |
|||
matrix: 2 0 0 |
|||
0 _1 0 |
|||
0 0 _1 |
|||
coefficients: 2 3 0 _1 |
|||
roots: 2 _1 _1 |
|||
errors: 0 0 0 |
|||
task 2 0,0 3 4,:0 4 9 |
|||
matrix: 2 0 0 |
|||
0 3 4 |
|||
0 4 9 |
|||
coefficients: 22 _35 14 _1 |
|||
roots: 11 2 1 |
|||
errors: 0 0 0 |
|||
task 1 0,0,.+.1ad_45 1ad45 |
|||
matrix: 1 0 0 |
|||
0 0.707107 _0.707107 |
|||
0 0.707107 0.707107 |
|||
coefficients: 1 _2.41421 2.41421 _1 |
|||
roots: 1 0.707107j0.707107 0.707107j_0.707107 |
|||
errors: 0 4.44089e_15j_1.77636e_15 4.44089e_15j1.77636e_15</syntaxhighlight> |
|||
We could instead use [[j:Vocabulary/LAPACK|lapack]]. The lapack approach would be more stable for very large matrices, but that's not an issue here. |
|||
=={{header|Julia}}== |
=={{header|Julia}}== |