Ask Your Question
0

How to check if a symbolic expression is numerically evaluable?

asked 2013-09-01 18:02:22 +0100

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"
edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
1

answered 2013-09-01 20:47:21 +0100

tmonteil gravatar image

updated 2013-09-01 20:49:41 +0100

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"
edit flag offensive delete link more
0

answered 2013-09-01 23:23:25 +0100

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
edit flag offensive delete link more

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 ( 2013-09-02 08:17:23 +0100 )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 09:34:51 +0100 )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: 2013-09-01 18:02:22 +0100

Seen: 865 times

Last updated: Sep 01 '13