eigenmath/abs.cpp

168 lines
1.9 KiB
C++
Raw Permalink Normal View History

2005-10-04 02:02:16 +02:00
// Absolute value, aka vector magnitude
2004-03-03 21:24:06 +01:00
#include "stdafx.h"
#include "defs.h"
void
eval_abs(void)
{
push(cadr(p1));
eval();
absval();
}
void
absval(void)
{
2005-10-04 02:02:16 +02:00
int h;
2008-05-10 18:33:14 +02:00
save();
2004-03-03 21:24:06 +01:00
p1 = pop();
2005-08-06 22:57:37 +02:00
if (istensor(p1)) {
2004-03-03 21:24:06 +01:00
absval_tensor();
2008-05-10 18:33:14 +02:00
restore();
2004-03-03 21:24:06 +01:00
return;
}
if (isnum(p1)) {
push(p1);
if (isnegativenumber(p1))
negate();
2008-05-10 18:33:14 +02:00
restore();
2004-03-03 21:24:06 +01:00
return;
}
if (iscomplexnumber(p1)) {
push(p1);
push(p1);
conjugate();
multiply();
push_rational(1, 2);
power();
2008-05-10 18:33:14 +02:00
restore();
2004-03-03 21:24:06 +01:00
return;
}
2005-10-04 02:02:16 +02:00
// abs(1/a) evaluates to 1/abs(a)
if (car(p1) == symbol(POWER) && isnegativeterm(caddr(p1))) {
push(p1);
reciprocate();
absval();
reciprocate();
2008-05-10 18:33:14 +02:00
restore();
2005-10-04 02:02:16 +02:00
return;
}
// abs(a*b) evaluates to abs(a)*abs(b)
if (car(p1) == symbol(MULTIPLY)) {
h = tos;
p1 = cdr(p1);
while (iscons(p1)) {
push(car(p1));
absval();
p1 = cdr(p1);
}
multiply_all(tos - h);
2008-05-10 18:33:14 +02:00
restore();
2005-10-04 02:02:16 +02:00
return;
}
2004-03-03 21:24:06 +01:00
if (isnegativeterm(p1) || (car(p1) == symbol(ADD) && isnegativeterm(cadr(p1)))) {
push(p1);
negate();
p1 = pop();
}
push_symbol(ABS);
push(p1);
list(2);
2008-05-10 18:33:14 +02:00
restore();
2004-03-03 21:24:06 +01:00
}
2006-01-04 02:47:50 +01:00
void
2004-03-03 21:24:06 +01:00
absval_tensor(void)
{
if (p1->u.tensor->ndim != 1)
stop("abs(tensor) with tensor rank > 1");
push(p1);
push(p1);
conjugate();
inner();
push_rational(1, 2);
power();
2008-05-10 18:33:14 +02:00
simplify();
eval();
2004-03-03 21:24:06 +01:00
}
2007-05-08 16:57:30 +02:00
#if SELFTEST
2004-03-03 21:24:06 +01:00
static char *s[] = {
"abs(2)",
"2",
"abs(2.0)",
"2",
"abs(-2)",
"2",
"abs(-2.0)",
"2",
"abs(a)",
"abs(a)",
"abs(-a)",
"abs(a)",
"abs(2*a)",
2005-10-04 02:02:16 +02:00
"2*abs(a)",
2004-03-03 21:24:06 +01:00
"abs(-2*a)",
2005-10-04 02:02:16 +02:00
"2*abs(a)",
2004-03-03 21:24:06 +01:00
"abs(2.0*a)",
2005-10-04 02:02:16 +02:00
"2*abs(a)",
2004-03-03 21:24:06 +01:00
"abs(-2.0*a)",
2005-10-04 02:02:16 +02:00
"2*abs(a)",
2004-03-03 21:24:06 +01:00
"abs(a-b)+abs(b-a)",
"2*abs(a-b)",
"abs(3 + 4 i)",
"5",
"abs((2,3,4))",
"29^(1/2)",
2005-10-04 02:02:16 +02:00
"abs(a*b)",
"abs(a)*abs(b)",
"abs(a/b)",
"abs(a)/abs(b)",
"abs(1/a^b)",
"1/(abs(a^b))",
2007-05-23 19:44:07 +02:00
2008-05-10 18:35:30 +02:00
// Check that vector length is simplified
2007-05-23 19:44:07 +02:00
"P=(u*cos(v),u*sin(v),v)",
"",
"abs(cross(d(P,u),d(P,v)))",
"(1+u^2)^(1/2)",
2004-03-03 21:24:06 +01:00
};
void
test_abs(void)
{
test(__FILE__, s, sizeof s / sizeof (char *));
}
2007-05-08 16:57:30 +02:00
#endif