(term: Expression)
| 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 | */ |
| 269 | export 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]); |
no test coverage detected