MCPcopy Create free account
hub / github.com/cortex-js/compute-engine / processTerm

Function processTerm

src/compute-engine/boxed-expression/polynomials.ts:240–318  ·  view source on GitHub ↗
(term: Expression)

Source from the content-addressed store, hash-verified

238 } else {
239 // Complex factor containing variable
240 return false;
241 }
242 }
243 return addCoefficient(coef, varDeg);
244 }
245
246 return false;
247 };
248
249 // Process the expanded expression
250 if (isFunction(expanded, 'Add')) {
251 for (const term of expanded.ops) {
252 if (!processTerm(term)) return null;
253 }
254 } else {
255 if (!processTerm(expanded)) return null;
256 }
257
258 return coeffs;
259}
260
261/**
262 * Construct a polynomial expression from its coefficients.
263 * coeffs[i] is the coefficient of x^i.
264 *
265 * Examples:
266 * - `fromCoefficients([1, 2, 0, 1], 'x')` → x^3 + 2x + 1
267 * - `fromCoefficients([5, -1, 3], 'x')` → 3x^2 - x + 5
268 */
269export function fromCoefficients(
270 coeffs: Expression[],
271 variable: string
272): Expression {
273 if (coeffs.length === 0) return coeffs[0]?.engine.Zero ?? null!;
274
275 const ce = coeffs[0].engine;
276 const x = ce.symbol(variable);
277 const terms: Expression[] = [];
278
279 for (let i = 0; i < coeffs.length; i++) {
280 const coef = coeffs[i];
281 if (coef.isSame(0)) continue;
282
283 if (i === 0) {
284 // Constant term
285 terms.push(coef);
286 } else if (i === 1) {
287 // Linear term
288 if (coef.isSame(1)) {
289 terms.push(x);
290 } else if (coef.isSame(-1)) {
291 terms.push(x.neg());
292 } else {
293 terms.push(coef.mul(x));
294 }
295 } else {
296 // Higher degree term
297 const xPow = ce.expr(['Power', variable, i]);

Callers 1

Calls 10

isSymbolFunction · 0.90
isFunctionFunction · 0.90
asSmallIntegerFunction · 0.90
polynomialDegreeFunction · 0.85
addCoefficientFunction · 0.85
isSameMethod · 0.65
negMethod · 0.65
hasMethod · 0.65
functionMethod · 0.65

Tested by

no test coverage detected