Ask Your Question
2

expression has trig component or not?

asked 2011-02-10 14:49:09 +0100

Shu gravatar image

updated 2011-04-28 18:06:31 +0100

Kelvin Li gravatar image

Is there any way in Sage to find out whether an expression has any trigonometric component (e.g. sin, cos,... ) or not?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2011-02-10 21:39:15 +0100

DSM gravatar image

updated 2011-02-11 02:22:38 +0100

There's probably an Expression walker lurking somewhere which could do what the first function does automatically but I don't know where it lives. So instead (with the usual untested warning):


def walk_for_operators(someexpr):
    tor = someexpr.operator()
    if tor: yield tor
    for oper in someexpr.operands():
        for subtor in walk_for_operators(oper):
            yield subtor

trig_ops = set([sin, cos, tan, sec, csc, cot, 
                sinh, cosh, tanh, sech, csch, coth,
                asin, acos, atan, asec, acsc, acot,
                asinh, acosh, atanh, asech, acsch, acoth,
                atan2])

def has_trig_fn(someexpr):
    return any(op in trig_ops for op in walk_for_operators(someexpr))
sage: x,y = var("x, y")
sage: list(walk_for_operators(x^2))
[<built-in function pow>]
sage: list(walk_for_operators(x^2+4))
[<built-in function add>, <built-in function pow>]
sage: list(walk_for_operators(x^2+4+sin(x)^2))
[<built-in function add>, <built-in function pow>, <built-in function pow>, sin]
sage: list(walk_for_operators((x^2+4+exp(x)^2)/(1-sin(y))))
[<built-in function mul>, <built-in function pow>, <built-in function add>, 
sin, <built-in function add>,<built-in function pow>, exp, <built-in function mul>]
sage: # hmm.  that's strange, no sub and div?
sage: list(walk_for_operators(x/y))
[<built-in function mul>, <built-in function pow>]
sage: (x/y).operands()
[x, 1/y]
sage: (x/y).operator()
<built-in function mul>
sage: (x/y).operands()[1]
1/y
sage: ((x/y).operands()[1]).operator()
<built-in function pow>
sage: # so it seems the division is processed to a pow (and sub to add with negative arg).  okay.
sage: 
sage: has_trig_fn(x^2+4)
False
sage: has_trig_fn(x^2+4+sin(x)^2)
True
sage: has_trig_fn((x^2+4+exp(x)^2)/(1-pow(atan2(x,y), 5)))
True
edit flag offensive delete link more

Comments

Thanks for your help.

Shu gravatar imageShu ( 2011-02-11 11:34:44 +0100 )edit

I agree that this is unwieldy, but it should work, and I don't know that we have any better way of walking the expression trees yet. @DSM, are you *sure* you'll be staying behind myself and Niles in karma? ;)

kcrisman gravatar imagekcrisman ( 2011-02-11 14:07:58 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

Stats

Asked: 2011-02-10 14:49:09 +0100

Seen: 440 times

Last updated: Feb 11 '11