Detect whether an expression could have an undefined result

98 views Asked by At

I would like to determine whether a given expression can have an undefined result.

For instance, take the following computation:

a = rand() * 1000  // a real number >=0 and <1000
b = trunc( a )*2   // an even number between 0 and 1998
c = sin( a )       // a real number >=-1 and <=1
d = pow( c, b )    // a positive real number >=0 and <=1
e = log( a )       // either undefined (-Infinity), or a real number <6.907…
f = sqrt( e )      // either undefined, or a real number >=0 and <2.628…

How can I write a program that tells me that e and f can be undefined, while the others are always defined?

Is there any library that can check this for me?

I'm currently writing in JavaScript, but I'm willing to change language if there's no such library for JS, but it's there for other languages.

1

There are 1 answers

1
Stef On

Using python and its library sympy, there is sympy.calculus.util.continuous_domain.

from sympy import Symbol
from sympy import sin, log, sqrt
from sympy.sets import Interval
from sympy.calculus.util import continuous_domain, function_range


a = Symbol('a')
b = 3

c = sin(a)
d = c ** b
e = log(a)
f = sqrt(e)

for y in (c,d,e,f):
    print(y)
    print('domain: ', continuous_domain(y, a, Interval(0,1000)))
    print('range:  ', function_range(y, a, Interval(0,1000)))
    print()

Output:

sin(a)
domain:  Interval(0, 1000)
range:   Interval(-1, 1)

sin(a)**3
domain:  Interval(0, 1000)
range:   Interval(-1, 1)

log(a)
domain:  Interval.Lopen(0, 1000)
range:   Interval(-oo, log(1000))

sqrt(log(a))
domain:  Interval(1, 1000)
range:   Interval(0, sqrt(log(1000)))

Unfortunately, replacing b = 3 with b = Symbol('b', integer = True) or b = floor(a) both result in a spectacular crash of function_range(d, a, Interval(0,1000)). You can still get the continuous_domain, but not the function_range.