Ask Your Question

How to check if a symbolic expression is numerically evaluable?

asked 2013-09-01 11:02:22 -0500

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()
     print "sorry, no"
edit retag flag offensive close merge delete

2 answers

Sort by » oldest newest most voted

answered 2013-09-01 13:47:21 -0500

tmonteil gravatar image

updated 2013-09-01 13:49:41 -0500

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:

    n = exp.n()
except TypeError:
    print "sorry, no"
edit flag offensive delete link more

answered 2013-09-01 16:23:25 -0500

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()


sage: is_numerically_evaluable(sin(1))
sage: is_numerically_evaluable(x)
edit flag offensive delete link more



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 ( 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.

petropolis gravatar imagepetropolis ( 2013-09-02 02:34:51 -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


Asked: 2013-09-01 11:02:22 -0500

Seen: 236 times

Last updated: Sep 01 '13