Search code examples
pythonnumpypde

How can write and indicator function in Python?


I want to make an indicator function for pde in Python u(x) = 2x if 0<x<1/2 and 2-2x if 1/2<x<1 but when i do it an error occurs.

I have chosen the np.where which is a if else function.

Can someone help me?

import numpy as np
x = np.linspace(0,1)
x
np.where(x>0 & x<1/2,2*x,2-2*x)

Solution

  • It would be really helpful if you provided the error message instead of just saying "an error occurs".

    Anyway, add parentheses, i.e. (x>0) & (x<0.5). You need them because the & operator has higher precedence than the comparison operators, so in x>0 & x<0.5, the first expression to be evaluated is 0 & x. The error message complains that this is not valid when x is a NumPy array.

    PS: This is not an indicator function.