Ask Your Question

How to robustly simplify an object (including a number)

asked 2011-12-19 09:14:40 +0200


When writing a package, I met the following problem:

Say, I want the variable 'a' to be an expression, which is passed to the package by user. Then I want to call a.simplify() to simplify the expression.

However, as an input, a could naturally be the following cases:

# case 1
a = var('t')
# case 2
a = 1
# case 3
a = 0.1

a.simplify() will work on 1, but not work on 2 or 3, which crashes the whole package.

I could do something as

    b = a.simplify()
    b = a

But this really seems like a workaround instead of something formal. Is there a better way to handle this case? Thanks!

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted

answered 2011-12-19 09:20:55 +0200

Jason Grout gravatar image

The simplify method exists on symbolic objects in Sage, but not on numbers. So I would either do your try/except block (but except the specific error about not having the simplify attribute), or test using hasattr whether you have the simplify attribute.

Alternatively, you could convert whatever the user passed in to a symbolic object:

edit flag offensive delete link more


There's also the simplify function, but that doesn't extend to the other members of the simplify_* set, so this is probably the most general sol'n. (I guess we could coerce back to the original type as well.)

DSM gravatar imageDSM ( 2011-12-19 09:25:56 +0200 )edit

@Jason Grout: Thanks a lot! Previously I naively tried Expression(a) without luck. SR(a) is what I was looking for.

tririver gravatar imagetririver ( 2011-12-19 09:50:50 +0200 )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


Asked: 2011-12-19 09:14:40 +0200

Seen: 347 times

Last updated: Dec 19 '11