2

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?

sloan
  • 319
  • 1
  • 3
  • 9

1 Answers1

3

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())
zmo
  • 24,463
  • 4
  • 54
  • 90
  • I was thinking about the same solution. Thanks for answering, it's kind of solution for me! – sloan Jun 13 '13 at 15:18
  • You may need to do `evalf(chop=True)` in general, to clear out small imaginary parts. – asmeurer Jun 14 '13 at 16:14
  • 1
    You want `not v.is_real`, not `v.is_imaginary`. `is_imaginary` is only for pure imaginary numbers. `(1 + 2*I).is_imaginary` will be `False`. – asmeurer Jun 14 '13 at 16:14