eigenmath/coeff.cpp

135 lines
1.7 KiB
C++
Raw Permalink Normal View History

2006-02-08 19:02:48 +01:00
// get the coefficient of x^n in polynomial p(x)
2004-03-03 21:24:06 +01:00
2006-02-07 18:38:33 +01:00
#include "stdafx.h"
2004-03-03 21:24:06 +01:00
#include "defs.h"
2006-02-08 19:02:48 +01:00
#define P p1
#define X p2
#define N p3
2006-02-07 18:38:33 +01:00
void
eval_coeff(void)
{
2006-02-08 19:02:48 +01:00
push(cadr(p1)); // 1st arg, p
2006-02-07 18:38:33 +01:00
eval();
push(caddr(p1)); // 2nd arg, x
eval();
2006-02-08 19:02:48 +01:00
push(cadddr(p1)); // 3rd arg, n
eval();
2006-02-07 18:38:33 +01:00
2006-02-08 19:02:48 +01:00
N = pop();
X = pop();
P = pop();
2006-02-07 18:38:33 +01:00
2006-02-08 19:02:48 +01:00
if (N == symbol(NIL)) { // only 2 args?
N = X;
X = symbol(SYMBOL_X);
}
2006-02-07 18:38:33 +01:00
2006-02-08 19:02:48 +01:00
push(P); // divide p by x^n
push(X);
push(N);
power();
divide();
2006-02-07 18:38:33 +01:00
2006-02-08 19:02:48 +01:00
push(X); // keep the constant part
filter();
2004-03-03 21:24:06 +01:00
}
2006-02-07 19:46:47 +01:00
//-----------------------------------------------------------------------------
//
// Put polynomial coefficients on the stack
//
// Input: tos-2 p(x)
//
// tos-1 x
//
// Output: Returns number of coefficients on stack
//
// tos-n Coefficient of x^0
//
// tos-1 Coefficient of x^(n-1)
//
//-----------------------------------------------------------------------------
2004-03-03 21:24:06 +01:00
int
coeff(void)
{
int h, n;
save();
p2 = pop();
p1 = pop();
h = tos;
for (;;) {
2006-02-07 19:46:47 +01:00
push(p1);
2004-03-03 21:24:06 +01:00
push(p2);
2004-06-25 22:45:15 +02:00
push(zero);
2004-03-03 21:24:06 +01:00
subst();
eval();
p3 = pop();
push(p3);
push(p1);
push(p3);
subtract();
p1 = pop();
2004-06-25 22:45:15 +02:00
if (equal(p1, zero)) {
2004-03-03 21:24:06 +01:00
n = tos - h;
restore();
return n;
}
push(p1);
push(p2);
divide();
p1 = pop();
}
}
2007-05-08 16:57:30 +02:00
#if SELFTEST
2004-03-03 21:24:06 +01:00
static char *s[] = {
2006-02-08 19:02:48 +01:00
"coeff(40*x^3+30*x^2+20*x+10,3)",
"40",
"coeff(40*x^3+30*x^2+20*x+10,2)",
"30",
"coeff(40*x^3+30*x^2+20*x+10,1)",
"20",
"coeff(40*x^3+30*x^2+20*x+10,0)",
"10",
"coeff(a*t^3+b*t^2+c*t+d,t,3)",
"a",
"coeff(a*t^3+b*t^2+c*t+d,t,2)",
"b",
2004-03-03 21:24:06 +01:00
2006-02-08 19:02:48 +01:00
"coeff(a*t^3+b*t^2+c*t+d,t,1)",
"c",
2004-03-03 21:24:06 +01:00
2006-02-08 19:02:48 +01:00
"coeff(a*t^3+b*t^2+c*t+d,t,0)",
"d",
2004-03-03 21:24:06 +01:00
};
void
test_coeff(void)
{
test(__FILE__, s, sizeof s / sizeof (char *));
}
2007-05-08 16:57:30 +02:00
#endif