# How to check if a symbolic expression is numerically evaluable?

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"

edit retag close merge delete

Sort by » oldest newest most voted

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"

more

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

more

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

( 2013-09-02 01:17:23 -0500 )edit

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

( 2013-09-02 02:34:51 -0500 )edit

## Stats

Seen: 236 times

Last updated: Sep 01 '13