First time here? Check out the FAQ!

Ask Your Question
0

How to robustly simplify an object (including a number)

asked 13 years ago

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!

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
2

answered 13 years ago

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()
Preview: (hide)
link

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 ( 13 years ago )

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

tririver gravatar imagetririver ( 13 years ago )

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: 13 years ago

Seen: 474 times

Last updated: Dec 19 '11