1

How can I ensure the following function is undefined outside of the closed domain [0,L] using the 'else' function? I define the endpoints and the interval (0,L) using if-statements. My code is below:

def u(x):
    if x=0:
        return A
    elif x=L:
        return B
    elif 0<x<L:
        return 0*x+10
    else:
timgeb
  • 76,762
  • 20
  • 123
  • 145
Andrew98
  • 41
  • 1
  • 6
  • Python functions aren't a perfect match to mathematical functions. The right thing to do here depends on your use case: you could return `None`, raise an exception, or something else. How are you using the function? What would be a reasonable thing to do if a negative number were passed in? – ChrisGPT was on strike Oct 27 '18 at 13:39

1 Answers1

1

Raise a ValueError with a helpful message in the else block,

raise ValueError('x must be in [0, {}]'.format(L))

for example. You could also create a custom DomainError inheriting from ValueError

class DomainError(ValueError):
    pass

and raise that.

In other parts of your code, you just call u and catch potential exceptions, following the EAFP principle.

edit:

If you need domain-checking for a number of math-like functions, you could also write yourself a simple decorator factory. Here's an example, depending on your use cases you might need to perform some minor modifications.

def domain(lower, upper):
    def wrap(f):
        def f_new(x):
            if not lower <= x <= upper:
               raise ValueError('x must be in [{}, {}]'.format(lower, upper))
            return f(x)
        return f_new
    return wrap

Demo:

>>> @domain(0, 10)
...:def f(x):
...:    return x + 1
...:
...:
>>> f(2)
>>> 3
>>> f(-1)
[...]
ValueError: x must be in [0, 10]
>>> f(10.1)
[...]
ValueError: x must be in [0, 10]
timgeb
  • 76,762
  • 20
  • 123
  • 145