Skip to content

Instantly share code, notes, and snippets.

@jakiestfu
Last active December 12, 2015 02:38
Show Gist options
  • Save jakiestfu/4700352 to your computer and use it in GitHub Desktop.
Save jakiestfu/4700352 to your computer and use it in GitHub Desktop.
Ported to JS from https://gist.github.com/4700257 by @kelleydv This is a function in python that accepts a list of arrays. The arrays represent the coefficients of a polynomial, in increasing degree. For example, the array (1,0,3) represents the polynomial 3x^2+1. The output is an array of lines of LaTeX code suitable for insertion into an enume…
/*
* polyTexMe
* @param polynomials: Array
* @return: Array
*
* polyTexMe takes a list of coefficient-arrays,
* where the degree of the term is equal to the index
*/
var polyTexMe = function(polynomials){
var someLatex = [],
i;
for(i in polynomials){
var coeffArray = polynomials[i],
rawPoly = [],
textLine = '',
order = 0,
j;
for(j in coeffArray){
var coefficient = coeffArray[j],
plusSign = '',
a = '', // will be the coeff for output
variable = '', // represents the variable factor of the term
texTerm = [];
if(coefficient != 0){
if(order > 1){
variable = 'x^{'+order+'}';
} else if(order == 1){
variable = 'x';
} else if(order == 0 && coefficient !=0){
a = coefficient;
}
if(coefficient*coefficient !=1){ // if the coeff is not 1 or -1
a = coefficient;
} else {
if(coefficient == -1){
if(order > 0){
a = '-';
} else {
a = '-1';
}
}
}
}
// do we need a '+' sign?
if(coefficient > 0 && order < coeffArray.length-1){
plusSign = '+';
}
texTerm = [plusSign, a, variable]; // putting this term together
rawPoly.push(texTerm.join('')); // adding it to the rest of the terms for this polynomial
order += 1;
}
rawPoly.reverse();
texLine = '\\item $'+(rawPoly.join(''))+'$'; // the actual LaTeX line
someLatex.push(texLine);
}
return someLatex;
};
/*
* Usage
*
* Insert an multidimensional array of your coefficients
* Output returns respective array of output.
*
* Expected and Actual Return:
*
* [ "\item $x^{3}-5x^{2}+3x$", "\item $8x^{4}+2x^{3}-1$", "\item $-3x^{3}+2x+4$" ]
*/
var x = [0,3,-5,1],
y = [-1,0,0,2,8],
z = [4,2,0,-3],
latex = polyTexMe([x, y, z]);
@jakiestfu
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment