Reputation: 329
I have a little question about sympy. I did load the library with :
from sympy import *
At some point of my program I would like to evaluate a function.
x=Symbol('x', real=True)
sqrt(1-x).subs(x, 9).evalf()
>>> 2.82842712474619*I
Sympy answer me complex value but i would like an error as in basic python :
sqrt(-1)
>>> ValueError: math domain error
Someone know how to do that using sympy?
Upvotes: 2
Views: 4185
Reputation: 24812
I may be wrong, but I don't think you can make it yell that way, because that's a scientific library so it is made for supporting imaginary numbers, but you can change it a bit:
x=Symbol('x', real=True)
v = sqrt(1-x).subs(x, 9).evalf()
if not v.is_real:
raise ValueError, "math domain error"
or you can create a function:
def assert_real(v):
if not v.is_real:
raise ValueError, "math domain error"
return v
so you can do:
x = Symbol('x', real=True)
v = assert_real(sqrt(1-x).subs(x, 9).evalf())
Upvotes: 3