First time here? Check out the FAQ!

Ask Your Question
0

How to check if a symbolic expression is numerically evaluable?

asked 11 years ago

petropolis gravatar image

Context: I want to evaluate a symbolic expression numerically; however sometimes this expression still depends on some symbolic parameters not yet assigned a value.

Question: What is the best way to avoid "TypeError: cannot evaluate symbolic expression numerically" in such a situation?

In other words, is there a function (or an equivalent construction) for

 if isThisSymbolicExpressionNumericallyEvaluabel(exp):
     n = exp.n()
 else: 
     print "sorry, no"
Preview: (hide)

2 Answers

Sort by » oldest newest most voted
1

answered 11 years ago

tmonteil gravatar image

updated 11 years ago

Python (therefore Sage) offers a try/except system to handle exceptions, see this page for more details.

In your case, you can write something like:

try:
    n = exp.n()
except TypeError:
    print "sorry, no"
Preview: (hide)
link
0

answered 11 years ago

Eviatar Bach gravatar image

You should be able to just check if it has no variables.

def is_numerically_evaluable(expr):
    return not expr.variables()

Then:

sage: is_numerically_evaluable(sin(1))
True
sage: is_numerically_evaluable(x)
False
Preview: (hide)
link

Comments

1

The `Symbolic Ring` is quite unpredictible, so that you may lose some opportunities, for example: sage: expr = integral(exp(-cos(x)), x, 0, 1) sage: expr integrate(e^(-cos(x)), x, 0, 1) sage: expr.parent() Symbolic Ring sage: expr.variables() (x,) sage: not expr.variables() False sage: expr.n() 0.4353513281039795

tmonteil gravatar imagetmonteil ( 11 years ago )

I woul prefer your method to the try/except method. I will wait to see if someone can make it watertight.

petropolis gravatar imagepetropolis ( 11 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: 11 years ago

Seen: 875 times

Last updated: Sep 01 '13