pythonsympyboolean-operationspiecewisefinite-element-analysis

How to Create Piecewise Function in SymPy with Intervals


i need to create a piece-wise function inside an interval but sympy piecewise can't use and (&). I read that the function can't recieve Boolean values so I tried to add them together and it doesn't seem to be right. The code is as follows:

import numpy as np
import sympy as sp
import matplotlib as plt  # This is all the library's i need
import mpmath

n = 10
x = sp.symbols('x', positive=True)
c = list(sp.symbols('c0:%d'%(n + 1)))
f = 1+(((sp.exp(x) * (1 - np.exp(-1))) + (sp.exp(-x)) * (np.exp(1) - 1)) / (np.exp(-1) - np.exp(1)))
xx = np.linspace(0, 1, n + 1)
i = 0
N = []
a = sp.Piecewise(
          (0, x < float(xx[i])),
          (((xx[i + 1] - x) / (xx[i + 1] - xx[i])), (x >= float((xx[i])))),
          ((xx[i + 1] - x) / (xx[i + 1] - xx[i]), x <= float((xx[i + 1]))),
          (0, x > float(xx[i + 1])),
          
)
N.append(a)

for i in range(1, n):
a = sp.Piecewise(
    (0, x < float(xx[i - 1])),
    ((xx[i - 1] - x) / xx[i - 1] - xx[i], x >= float((xx[i - 1]))),
    ((xx[i - 1] - x) / (xx[i - 1] - xx[i]), x <= float(xx[i])),
    (0, x > float(xx[i])),
    
)
b = sp.Piecewise(
    (0, x < float(xx[i])),
    ((xx[i + 1] - x) / (xx[i + 1] - xx[i]), x >= float(xx[i])),
    ((xx[i + 1] - x) / (xx[i + 1] - xx[i]), x <= float(xx[i + 1])),
    (0, x > float(xx[i + 1])),
    
)
N.append(a + b)

i = i + 1

a = sp.Piecewise(
(0, x < float(xx[i - 1])),
((xx[i - 1] - x) / (xx[i - 1] - xx[i]), x >= float((xx[i - 1]))),
((xx[i - 1] - x) / (xx[i - 1] - xx[i]), x <= float(xx[i])),
(0, x > float(xx[i])),

)
N.append(a)

Solution

  • It would be helpful if you give an example of how Piecewise did not do what you wanted. Piecewise will work with And (and intervals expressed with the same):

    enter image description here