Ask Your Question
0

How to robustly simplify an object (including a number)

asked 2011-12-19 02:14:40 -0500

Hi,

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

try:
    b = a.simplify()
except:
    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
2

answered 2011-12-19 02:20:55 -0500

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:

a=SR(a)
a.simplify()
edit flag offensive delete link more

Comments

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 02:25:56 -0500 )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 02:50:50 -0500 )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-12-19 02:14:40 -0500

Seen: 144 times

Last updated: Dec 19 '11